Home > Backend Development > Python Tutorial > How do I add seconds to a `datetime.time` object in Python?

How do I add seconds to a `datetime.time` object in Python?

Mary-Kate Olsen
Release: 2024-11-03 20:54:02
Original
985 people have browsed it

How do I add seconds to a `datetime.time` object in Python?

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>
Copy after login

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>
Copy after login

Example usage:

<code class="python">a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template