Monday, April 25, 2011

python time + timedelta equivalent

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

From stackoverflow
  • 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.

    Antonius Common : yes, nice answer. I should have made it trickier, like: time() + timedelta(minutes=30)
    sth : Yeah, then it gets messier..
    J.F. Sebastian : 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`
    sth : 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...
  • 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()
    
    J.F. Sebastian : +1: for `datetime` module. Otherwise it would require to deal with Overflow errors and such manually.
  • 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
    
    Antonius Common : silly me, didn't read it thoroughly!

0 comments:

Post a Comment