简体   繁体   English

从几分钟创建一个时间对象

[英]Create a time object from minutes

I am trying to create a time object to save to my database. 我正在尝试创建一个时间对象以保存到我的数据库。 Here is what I have so far: 这是我到目前为止的内容:

>>> minutes=137
>>> import datetime
>>> datetime.time(minute=minutes)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: minute must be in 0..59

How would I create a time object with more than 59 minutes? 如何创建超过59分钟的时间对象?

datetime.time() objects model a time of day , not a duration . datetime.time()对象模拟一天中时间 ,而不是持续时间 Unless you want your 137 minutes to be interpreted as 137 minutes after midnight , you should not be using datetime.time() objects. 除非您希望将137分钟解释为午夜之后的 137分钟,否则不应使用datetime.time()对象。

Use datetime.timedelta() for durations: 使用datetime.timedelta()作为持续时间:

>>> import datetime
>>> minutes = 137
>>> datetime.timedelta(minutes=minutes)
datetime.timedelta(0, 8220)

The timedelta object tracks time durations in days and seconds. timedelta对象以天和秒为单位跟踪持续时间。

If you did mean for the time to be interpreted as 2:17am you'll need to calculate the hours and remainder: 如果你没有意思的时候被解释为2:17我就需要计算时间和剩余:

>>> hour, minute = divmod(minutes, 60)
>>> datetime.time(hour, minute)
datetime.time(2, 17)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM