What is the standard way to add N seconds to datetime.time in Python? What is the standard way to add N seconds to datetime.time in Python? python python

What is the standard way to add N seconds to datetime.time in Python?

You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.

For example:

import datetimea = datetime.datetime(100,1,1,11,34,59)b = a + datetime.timedelta(0,3) # days, seconds, then other fields.print(a.time())print(b.time())

results in the two values, three seconds apart:


You could also opt for the more readable

b = a + datetime.timedelta(seconds=3)

if you're so inclined.

If you're after a function that can do this, you can look into using addSecs below:

import datetimedef 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)print(a)print(b)

This outputs:

 09:11:55.775695 09:16:55

As others here have stated, you can just use full datetime objects throughout:

from datetime import datetime, date, time, timedeltasometime = time(8,00) # 8amlater = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()

However, I think it's worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?

Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.

One little thing, might add clarity to override the default value for seconds

>>> b = a + datetime.timedelta(seconds=3000)>>> bdatetime.datetime(1, 1, 1, 12, 24, 59)