Antonius Common
Antonius Common

Reputation: 3031

python time + timedelta equivalent

I'm trying to do something like this:

time() + timedelta(hours=1)

however, Python doesn't allow it, apparently for good reason.

Does anyone have a simple work around?

Related:

Upvotes: 106

Views: 192669

Answers (7)

Santos Pb
Santos Pb

Reputation: 11

Have you tried relativedelta from the dateutil package? It seems to solve your problem quite nicely.

import datetime
from dateutil import relativedelta

print(datetime.datetime.now() + relativedelta.relativedelta(hours=1))
>>> 2023-05-09 16:35:57.008271

I also use it to manipulate dates, some examples:

# going back one month from today
end_date = datetime.date.today() - relativedelta.relativedelta(months=1)
print(end_date)
>>> 2023-04-09

# going back one month from January 2023
end_date = datetime.date(2023,1,1) - relativedelta.relativedelta(months=1)
print(end_date)
>>> 2022-12-01


Hope it helps!

Upvotes: 0

anon
anon

Reputation: 11

A little bit late to the party but you can also do something along the lines of:

init_time = time(4,0)
added_time = 8
new_time = datetime.time(init_time.hour+added_time)

Note that you'll need to add in correction code to make sure init+time.hour + added+time do not go above 23,59.

Upvotes: 1

yiming
yiming

Reputation: 77

You can change time() to now() for it to work

from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)

Upvotes: 5

rescdsk
rescdsk

Reputation: 8895

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

Upvotes: 15

jfs
jfs

Reputation: 414235

The solution is in the link that you provided in your question:

datetime.combine(date.today(), time()) + timedelta(hours=1)

Full example:

from datetime import date, datetime, time, timedelta

dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()

Output:

00:25:00

Upvotes: 162

sth
sth

Reputation: 229603

Workaround:

t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)

You can also omit the microseconds, if you don't need that much precision.

Upvotes: 10

Ali Afshar
Ali Afshar

Reputation: 41643

This is a bit nasty, but:

from datetime import datetime, timedelta

now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()

Upvotes: 7

Related Questions