How do I get time from a datetime.timedelta object?

It’s strange that Python returns the value as a datetime.timedelta. It probably should return a datetime.time. Anyway, it looks like it’s returning the elapsed time since midnight (assuming the column in the table is 6:00 PM). In order to convert to a datetime.time, you can do the following::

value = datetime.timedelta(0, 64800)
(datetime.datetime.min + value).time()

datetime.datetime.min and datetime.time() are, of course, documented as part of the datetime module if you want more information.

A datetime.timedelta is, by the way, a representation of the difference between two datetime.datetime values. So if you subtract one datetime.datetime from another, you will get a datetime.timedelta. And if you add a datetime.datetime with a datetime.timedelta, you’ll get a datetime.datetime. That’s how the code above works.

Leave a Comment