How to convert a time object to seconds since midn

2019-09-08 12:42发布

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条回答
来,给爷笑一个
2楼-- · 2019-09-08 13:23

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
查看更多
混吃等死
3楼-- · 2019-09-08 13:33

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.

查看更多
登录 后发表回答