How do I add n seconds to datetime.time?

Asked 2 years ago, Updated 2 years ago, 164 views

How do I add n seconds to datetime.time?

11:34:59 + 3 = 11:35:02

I wonder how to use it if I want to add it right away. I tried this way, but it didn't work, so I'm not sure what to do ㅜ<

import datetime

mytime = datetime.time(11, 34, 59)+3
print(mytime)
    mytime = datetime.time(11, 34, 59)+3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
import datetime

mytime = datetime.time(11, 34, 59)+datetime.timedelta(0,3)
print(mytime)
    mytime = datetime.time(11, 34, 59)+datetime.timedelta(0,3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
import datetime

mytime = datetime.time(11, 34, 59)+datetime.time(0,0,3)
print(mytime)
    mytime = datetime.time(11, 34, 59)+datetime.time(0,0,3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

datetime time python math

2022-09-22 14:31

1 Answers

Normal

Run in the same step.

import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(seconds=3)
print a.time()
print b.time()

Result:

11:34:59
11:35:02

To define a function in a more manual way,

import datetime

def addSecs(tm, secs):
    fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
    fulldate = fulldate + datetime.timedelta(seconds=secs)
    return fulldate.time()

a = datetime.datetime.now().time()
b = addSecs(a, 300)


2022-09-22 14:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.