Tony Beta Lambda
Tony Beta Lambda

Reputation: 571

How to convert a time object to seconds since midnight in python?

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?

Upvotes: 3

Views: 7120

Answers (2)

jfs
jfs

Reputation: 414149

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.

Upvotes: 3

xnx
xnx

Reputation: 25478

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

Upvotes: 7

Related Questions