如何在两个datetime对象之间以分钟为单位区分时间?


当前回答

要查找天数:timedelta有一个'days'属性。你可以简单地查询一下。

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

其他回答

Python 2.7新增了timedelta实例方法.total_seconds()。在Python文档中,这相当于(td。微秒+ (td。秒+ td。天* 24 * 3600)* 10**6)/ 10**6。

参考: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

这是我使用mktime的方法。

from datetime import datetime, timedelta
from time import mktime

yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()

difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60

这将给出以秒为单位的差值(然后除以60得到分钟):

import time
import datetime

t_start = datetime.datetime.now()

time.sleep(10)

t_end = datetime.datetime.now()
elapsedTime = (t_end - t_start )

print(elapsedTime.total_seconds())

输出:

10.009222

在我看来,这是最简单的方法,您不需要担心精度或溢出问题。

例如,使用elapsedTime。秒你失去了很多精度(它返回一个整数)。同时,elapsedTime。正如这个答案所指出的,微秒的上限是10^6。因此,例如,对于10秒的sleep(), elapsedTime。微秒给出8325(这是错误的,应该是10,000,000左右)。

这是为了找出当前时间和上午9:30之间的差值

t=datetime.now()-datetime.now().replace(hour=9,minute=30)

我用的是这样的:

from datetime import datetime

def check_time_difference(t1: datetime, t2: datetime):
    t1_date = datetime(
        t1.year,
        t1.month,
        t1.day,
        t1.hour,
        t1.minute,
        t1.second)

    t2_date = datetime(
        t2.year,
        t2.month,
        t2.day,
        t2.hour,
        t2.minute,
        t2.second)

    t_elapsed = t1_date - t2_date

    return t_elapsed

# usage 
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)

print(elapsed_time)
#return : 0:08:52