tags:

views:

2152

answers:

3

I'm trying to do something like this:

time() + timedelta(hours=1)

however, python has no allowance for it, apparently for good reason http://bugs.python.org/issue1487389

Does anyone have a simple work around?

Related

A: 

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.

sth
yes, nice answer.I should have made it trickier, like:time() + timedelta(minutes=30)
Antonius Common
Yeah, then it gets messier..
sth
s/. t.second/, t.second/
J.F. Sebastian
If `t == time(23,59)` then this approach won't work. When you add `1` to `t.hour` you'll get `ValueError: hour must be in 0..23`
J.F. Sebastian
Corrected the syntax error. For the 23:59 case the question is what the real intention of the calculation is, what you really want to get as a result in that case. I assumed it should stay on the same day (or give an error), else you usually would have datetime in the first place...
sth
+2  A: 

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()
Ali A
+1: for `datetime` module. Otherwise it would require to deal with Overflow errors and such manually.
J.F. Sebastian
+9  A: 

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
J.F. Sebastian
silly me, didn't read it thoroughly!
Antonius Common