2

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?

Tony Beta Lambda
  • 529
  • 3
  • 18

2 Answers2

5

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
xnx
  • 24,509
  • 11
  • 70
  • 109
2

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670