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


当前回答

这可能会帮助一些人,用这个方法找到过期与否其计算天数。这是dt。秒和dt。微秒也可用

from datetime import datetime
# updated_at = "2022-10-20T07:18:56.950563"
def is_expired(updated_at):
    expires_in = 7 #days
    datetime_format = '%Y-%m-%dT%H:%M:%S.%f'
    time_difference = datetime.now() - datetime.strptime(updated_at, datetime_format)

    return True if time_difference.days > expires_in else False

其他回答

只要用一个减去另一个。你会得到一个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)
>>> dd = d2 - d1
>>> print (dd.days) # get days
>>> print (dd.seconds) # get seconds
>>> print (dd.microseconds) # get microseconds
>>> print (int(round(dd.total_seconds()/60, 0))) # get minutes

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

    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上测试

只是认为在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

用其他方法得到日期之间的差异;

import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

得到最小值的输出。

谢谢

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