如何在python中找到两个日期时间对象之间的时差?

本文翻译自: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.daysdd.secondsdd.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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值