One of Python's strengths is its exhaustive library. And date and time management is an integral part of this, provided by the datetime module. datetime provides the classes datetime, date, time, timedelta and tzoffset.
Logic suggests that timedelta provides a convenient means to represent time intervals which can later be added (or subtracted) from the other types. Trouble is, only datetime class supports operations with timedelta. That is code like this would produce an error:
So how do you add (or subtract) a timedelta object from a time(or
Logic suggests that timedelta provides a convenient means to represent time intervals which can later be added (or subtracted) from the other types. Trouble is, only datetime class supports operations with timedelta. That is code like this would produce an error:
>>> from datetime import datetime, date, time, timedelta >>> dt1 = datetime.now() >>> td1 = timedelta(hours=1) >>> dt1 + td1 datetime.datetime(2014, 6, 26, 15, 38, 27, 149200) # OK >>> dt1.time()+td1 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
So how do you add (or subtract) a timedelta object from a time(or
date
) object? It turns out that a slightly convoluted way exists. Given a time object t1 and timedelta object td1, the following code does the trick.>>> (datetime.combine(datetime.now().date(), t1)+td1).time() datetime.time(15, 40, 55, 672503)There is probably a shorter and better way to accomplish, but at the moment this is what I could come up with.
Comments
Post a Comment