t1 = datetime.datetime(2013, 6, 6, 8, 30, 0)
t5 = datetime.datetime(2013, 6, 6, 10, 30, 0)
mytime = t5 - t1
如何在几分钟内得到结果?(多少分钟)
答案 0 :(得分:3)
如果t1
和t5
为datetime.datetime
个对象,则减去它们会为您提供datetime.timedelta
结果。
timedelta
对象以天,秒和微秒进行处理,但使用timedelta.total_seconds()
方法,您可以将秒数作为浮点值。只需将60除以分钟计数:
minutes = mytime.total_seconds() // 60
如果您还想要余数秒,请使用divmod()
函数:
minutes, seconds = divmod(mytime.total_seconds(), 60)
演示:
>>> import datetime
>>> t1 = datetime.datetime(2013, 6, 6, 8, 30, 0)
>>> t5 = datetime.datetime(2013, 6, 6, 10, 30, 0)
>>> mytime = t5 - t1
>>> mytime
datetime.timedelta(0, 7200)
>>> mytime.total_seconds() // 60
120.0
>>> divmod(mytime.total_seconds(), 60)
(120.0, 0.0)
答案 1 :(得分:0)
在Python 3中:
mytime_in_minutes = mytime / timedelta(minutes=1)
完整示例:
>>> from datetime import datetime, timedelta
>>> t1 = datetime(2013, 6, 6, 8, 30, 0)
>>> t5 = datetime(2013, 6, 6, 10, 30, 0)
>>>
>>> mytime = t5 - t1
>>> mytime / timedelta(minutes=1)
120.0
>>> mytime // timedelta(minutes=1)
120
>>> divmod(mytime, timedelta(minutes=1))
(120, datetime.timedelta(0))