如何在python中将时间对象转换为自午夜以来的秒数? [英] How to convert a time object to seconds since midnight in python?

查看:49
本文介绍了如何在python中将时间对象转换为自午夜以来的秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中有一个 datetime.time 对象(没有日期部分),想知道自午夜以来已经过去了多少秒.t.hour * 3600 + t.minute * 60 + t.second 肯定能用,但是有没有更pythonic的方法?

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?

推荐答案

你可以使用 datetime.combine() 创建一个 datetime 对象,得到 时间增量:

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

它支持微秒和任何其他未来的datetime.time.resolution.

It supports microseconds and any other future datetime.time.resolution.

这篇关于如何在python中将时间对象转换为自午夜以来的秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆