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


当前回答

这是我使用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

其他回答

这是我使用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

只是认为在timedelta方面提到格式化可能是有用的。Strptime()根据格式解析表示时间的字符串。

from datetime import datetime

datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'    
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'  
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)

这将输出: 0:05:00.518000

这里有一个很容易概括或转化为函数的答案,它合理紧凑,易于遵循。

ts_start=datetime(2020, 12, 1, 3, 9, 45)
ts_end=datetime.now()
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
days,secs=divmod(secs,secs_per_day:=60*60*24)
hrs,secs=divmod(secs,secs_per_hr:=60*60)
mins,secs=divmod(secs,secs_per_min:=60)
secs=round(secs, 2)
answer='Duration={} days, {} hrs, {} mins and {} secs'.format(int(days),int(hrs),int(mins),secs)
print(answer)

它给出的答案是“持续时间=270天10小时32分42.13秒”

你可能会发现这个快速的片段在不那么长的时间间隔里很有用:

    from datetime import datetime as dttm
    time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
    delta = dttm.now() - time_ago
    days = delta.days # can be converted into years which complicates a bit…
    hours, minutes, seconds = map(int, delta.__format__('').split('.')[0].split(' ')[-1].split(':'))

在Python v.3.8.6上测试

这就是我如何获得两个datetime之间经过的小时数。datetime对象:

before = datetime.datetime.now()
after  = datetime.datetime.now()
hours  = math.floor(((after - before).seconds) / 3600)