Adding Seconds to datetime.time in Python
Unlike basic arithmetic operations, adding seconds to a datetime.time object requires a more nuanced approach. This is because datetime.time doesn't support direct addition of integers.
Standard Method via datetime Conversion:
The preferred method involves converting datetime.time to a full datetime object, adding seconds using datetime.timedelta, and then extracting the time value:
<code class="python">import datetime a = datetime.datetime(100, 1, 1, 11, 34, 59) b = a + datetime.timedelta(seconds=3) # Days, seconds, then other fields print(a.time()) print(b.time())</code>
Custom Function using timedelta:
Alternatively, you can create a custom function like addSecs:
<code class="python">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()</code>
Example usage:
<code class="python">a = datetime.datetime.now().time() b = addSecs(a, 300) print(a) print(b)</code>
The above is the detailed content of How do I add seconds to a `datetime.time` object in Python?. For more information, please follow other related articles on the PHP Chinese website!