本文翻译自:How do I find the time difference between two datetime objects in python?
如何分辨两个datetime
对象之间的时差(以分钟为单位)?
#1楼
参考:https://stackoom.com/question/5e6t/如何在python中找到两个日期时间对象之间的时差
#2楼
New at Python 2.7 is the timedelta
instance method .total_seconds()
. timedelta
实例方法.total_seconds()
是Python 2.7的新功能。 From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
. 在Python文档中,这等效于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
。
Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds 参考: http : //docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds
#3楼
Just subtract one from the other. 只需从另一个中减去一个即可。 You get a timedelta
object with the difference. 您会得到一个带有差异的timedelta
对象。
>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)
You can convert dd.days
, dd.seconds
and dd.microseconds
to minutes. 您可以将dd.days
, dd.seconds
和dd.microseconds
转换为分钟。
#4楼
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 86400 + c.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
#5楼
This is how I get the number of hours that elapsed between two datetime.datetime objects: 这是我如何获取两个datetime.datetime对象之间经过的小时数:
before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
#6楼
Use divmod: 使用divmod:
now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past
d = divmod(now-then,86400) # days
h = divmod(d[1],3600) # hours
m = divmod(h[1],60) # minutes
s = m[1] # seconds
print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)