I have a datetime.time object (no date part) in python, and want to find out how many seconds has elapsed since midnight. t.hour * 3600 + t.minute * 60 + t.second will surely work, but is there a more pythonic way?
2 Answers
Unfortunately, it seems you can't get a timedelta object from two datetime.time objects. However, you can build one and use it with total_seconds() to get the number of seconds since midnight:
In [63]: t = datetime.time(hour=12, minute=57, second=12) # for example In [64]: datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second).total_seconds() Out[64]: 46632.0 Comments
You could use datetime.combine() to create a datetime object, to get timedelta:
from datetime import datetime, timedelta td = datetime.combine(datetime.min, t) - datetime.min seconds = td.total_seconds() # Python 2.7+ integer_milliseconds = td // timedelta(milliseconds=1) # Python 3 It supports microseconds and any other future datetime.time.resolution.