Adding Seconds to datetime.time in Python
Adding an integer number of seconds to a datetime.time value in Python is not immediately straightforward. Attempts to add a timedelta or another datetime.time object result in errors.
Naive Approaches
Basic attempts such as:
<code class="python">datetime.time(11, 34, 59) + 3 datetime.time(11, 34, 59) + datetime.timedelta(0, 3) datetime.time(11, 34, 59) + datetime.time(0, 0, 3)</code>
all fail with type errors.
Manual Conversion
One solution involves converting the datetime.time to seconds, adding the desired seconds, and then reconstructing the datetime.time object:
<code class="python">def add_secs_to_time(timeval, secs_to_add): secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second secs += secs_to_add return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)</code>
Using datetime.datetime
A more convenient method is to use a full datetime.datetime object, setting it to a dummy date and then using the time() method to retrieve just the time value. For example:
<code class="python">a = datetime.datetime(100, 1, 1, 11, 34, 59) b = a + datetime.timedelta(0, 3) print(a.time()) print(b.time())</code>
Results in:
11:34:59 11:35:02
Alternatively, you can use:
<code class="python">b = a + datetime.timedelta(seconds=3)</code>
Custom Function
If a custom function is desired, you can define one that utilizes the addSecs method:
<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>
This method accepts a datetime.time object and an integer representing the number of seconds to add, returning the modified time.
The above is the detailed content of How can I add seconds to a datetime.time object in Python?. For more information, please follow other related articles on the PHP Chinese website!