Convert datetime.time into datetime.timedelta in Python 3.4

Rob Murray picture Rob Murray · Feb 6, 2016 · Viewed 19.2k times · Source

I am trying to convert two "durations", however I am currently receiving a TypeError due to one being a datetime.timedelta and one being a datetime.time:

TypeError: unorderable types: datetime.time() <= datetime.timedelta()

What is an efficient way to convert a datetime.time to a datetime.timedelta?

I have checked the docs and there is no built-in method for conversion between these two types.

Answer

Martijn Pieters picture Martijn Pieters · Feb 6, 2016

datetime.time() is not a duration, it is a point in a day. If you want to interpret it as a duration, then convert it to a duration since midnight:

datetime.combine(date.min, timeobj) - datetime.min

Demo:

>>> from datetime import datetime, date, time
>>> timeobj = time(12, 45)
>>> datetime.combine(date.min, timeobj) - datetime.min
datetime.timedelta(0, 45900)

You may need to examine how you get the datetime.time() object in the first place though, perhaps there is a shorter path to a timedelta() from the input data you have? Don't use datetime.time.strptime() for durations, for example.