Python 将 datetime.time 转换为秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44823073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert datetime.time to seconds
提问by Bluefire
I have an object of type datetime.time
. How do I convert this to an int representing its duration in seconds? Or to a string, which I can then convert to a second representation by splitting?
我有一个类型的对象datetime.time
。如何将其转换为以秒为单位表示其持续时间的 int?或者到一个字符串,然后我可以通过拆分将其转换为第二个表示?
回答by bakatrouble
You can calculate it by yourself:
你可以自己计算:
from datetime import datetime
t = datetime.now().time()
seconds = (t.hour * 60 + t.minute) * 60 + t.second
回答by Kruup?s
You need to convert your datetime.time
object into a datetime.timedelta
to be able to use total_seconds()
function.
您需要将datetime.time
对象转换为 adatetime.timedelta
才能使用total_seconds()
函数。
It will return a float
rather than an int as asked in the question but you can easily cast it.
它将返回 afloat
而不是问题中所问的 int ,但您可以轻松地投射它。
>>> from datetime import datetime, date, time, timedelta
>>> timeobj = time(12, 45)
>>> t = datetime.combine(date.min, timeobj) - datetime.min
>>> isinstance(t, timedelta)
# True
>>> t.total_seconds()
45900.0
Links I've be inspired by:
我受到启发的链接:
回答by Thierry Lathuille
If your object is supposed to represent a duration, you should use a datetime.timedelta
instead of a datetime.time
.
如果您的对象应该表示持续时间,则应使用 adatetime.timedelta
而不是 a datetime.time
。
datetime.time objectsare meant to represent a time of the day.
datetime.time 对象用于表示一天中的时间。
datetime.timedelta objectsare meant to represent a duration, and have a total_seconds()
method that does exactly what you want.
datetime.timedelta 对象旨在表示持续时间,并且具有total_seconds()
完全符合您要求的方法。
回答by Kostas
As @Owl Max proposed the easiest way to have an integer representation of a time is to use a timedelta. Although, I would like to share a different way to construct the timedelta.
正如@Owl Max 提出的那样,用整数表示时间的最简单方法是使用 timedelta。虽然,我想分享一种不同的方式来构建 timedelta。
A useful one-liner I like to use is:
我喜欢使用的一个有用的单行是:
import datetime
t = datetime.time(10, 0, 5)
int(datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second).total_seconds())
(ps. Normally this would be a comment)
(ps。通常这将是一个评论)