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

如何在python中找到两个datetime对象之间的时间差?,python,datetime,date-arithmetic,Python,Datetime,Date Arithmetic,我如何判断两个datetime对象之间的时差(以分钟为单位)?只需从另一个对象中减去一个即可。您将得到一个具有差异的timedelta对象 >>> import datetime >>> d1 = datetime.datetime.now() >>> d2 = datetime.datetime.now() # after a 5-second or so pause >>> d2 - d1 datetime.timede

我如何判断两个
datetime
对象之间的时差(以分钟为单位)?

只需从另一个对象中减去一个即可。您将得到一个具有差异的
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.days
dd.seconds
dd.microseconds
转换为分钟

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds
从第一次
difference=later\u time-first\u time
中减去后面的时间将创建一个只保存差异的datetime对象。
在上面的示例中,它是0分8秒562000微秒。

Python 2.7中新增的
timedelta
实例方法
。total_seconds()
。从Python文档来看,这相当于
(td.microseconds+(td.seconds+td.days*24*3600)*10**6)/10**6

参考:


这是如何获取两个datetime.datetime对象之间经过的小时数:

before = datetime.datetime.now()
after  = datetime.datetime.now()
hours  = math.floor(((after - before).seconds) / 3600)
使用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)
这是我使用的方法


如果
a
b
是日期时间对象,那么在Python 3中查找它们之间的时间差:

from datetime import timedelta

time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)
在早期Python版本上:

time_difference_in_minutes = time_difference.total_seconds() / 60

如果
a
b
是原始的日期时间对象,如
datetime.now()
返回的日期时间对象,则如果这些对象表示具有不同UTC偏移量的本地时间,例如DST转换前后或过去/未来日期,则结果可能是错误的。更多详细信息:


要获得可靠的结果,请使用UTC time或时区感知的datetime对象。

仅查找天数:timedelta具有“天”属性。你可以简单地查询一下

>>>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

我只是觉得在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

使用日期时间示例

>>> from datetime import datetime
>>> then = datetime(2012, 3, 5, 23, 8, 15)        # Random date in the past
>>> now  = datetime.now()                         # Now
>>> duration = now - then                         # For build-in functions
>>> duration_in_s = duration.total_seconds()      # Total number of seconds between dates
持续时间(年)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
持续时间(天)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
持续时间(小时)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
持续时间(分钟)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
持续时间(秒)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
[!]请参阅本文底部关于使用持续时间(秒)的警告

持续时间(微秒)

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
[!]请参阅本文底部关于使用持续时间(微秒)的警告

两个日期之间的总持续时间

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60
>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
或者简单地说:

>>> print(now - then)

编辑2019 由于这个答案已经得到了广泛的关注,我将添加一个函数,它可能会简化一些应用程序的使用

from datetime import datetime

def getDuration(then, now = datetime.now(), interval = "default"):

    # Returns a duration as specified by variable interval
    # Functions, except totalDuration, returns [quotient, remainder]

    duration = now - then # For build-in functions
    duration_in_s = duration.total_seconds() 
    
    def years():
      return divmod(duration_in_s, 31536000) # Seconds in a year=31536000.

    def days(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 86400) # Seconds in a day = 86400

    def hours(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 3600) # Seconds in an hour = 3600

    def minutes(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 60) # Seconds in a minute = 60

    def seconds(seconds = None):
      if seconds != None:
        return divmod(seconds, 1)   
      return duration_in_s

    def totalDuration():
        y = years()
        d = days(y[1]) # Use remainder to calculate next variable
        h = hours(d[1])
        m = minutes(h[1])
        s = seconds(m[1])

        return "Time between dates: {} years, {} days, {} hours, {} minutes and {} seconds".format(int(y[0]), int(d[0]), int(h[0]), int(m[0]), int(s[0]))

    return {
        'years': int(years()[0]),
        'days': int(days()[0]),
        'hours': int(hours()[0]),
        'minutes': int(minutes()[0]),
        'seconds': int(seconds()),
        'default': totalDuration()
    }[interval]

# Example usage
then = datetime(2012, 3, 5, 23, 8, 15)
now = datetime.now()

print(getDuration(then)) # E.g. Time between dates: 7 years, 208 days, 21 hours, 19 minutes and 15 seconds
print(getDuration(then, now, 'years'))      # Prints duration in years
print(getDuration(then, now, 'days'))       #                    days
print(getDuration(then, now, 'hours'))      #                    hours
print(getDuration(then, now, 'minutes'))    #                    minutes
print(getDuration(then, now, 'seconds'))    #                    seconds
警告:关于内置的.s和.微秒的警告
datetime.seconds
datetime.microseconds
分别上限为[086400]和[0,10^6]

如果timedelta大于最大返回值,则应小心使用

示例:

end
start
之后的1h和200μs:

>>> start = datetime(2020,12,31,22,0,0,500)
>>> end = datetime(2020,12,31,23,0,0,700)
>>> delta = end - start
>>> delta.microseconds
RESULT: 200
EXPECTED: 3600000200
>>> start = datetime(2020,12,30,22,0,0)
>>> end = datetime(2020,12,31,23,0,0)
>>> delta = end - start
>>> delta.seconds
RESULT: 3600
EXPECTED: 90000
end
start
之后的1d和1h:

>>> start = datetime(2020,12,31,22,0,0,500)
>>> end = datetime(2020,12,31,23,0,0,700)
>>> delta = end - start
>>> delta.microseconds
RESULT: 200
EXPECTED: 3600000200
>>> start = datetime(2020,12,30,22,0,0)
>>> end = datetime(2020,12,31,23,0,0)
>>> delta = end - start
>>> delta.seconds
RESULT: 3600
EXPECTED: 90000

以其他方式获取日期之间的差异

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)
所以以分钟为单位获得输出


谢谢

我用了这样的东西:

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

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

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

我已经使用时间差进行了持续集成测试,以检查和改进我的函数

from datetime import datetime

class TimeLogger:
    time_cursor = None

    def pin_time(self):
        global time_cursor
        time_cursor = datetime.now()

    def log(self, text=None) -> float:
        global time_cursor

        if not time_cursor:
            time_cursor = datetime.now()

        now = datetime.now()
        t_delta = now - time_cursor

        seconds = t_delta.total_seconds()

        result = str(now) + ' tl -----------> %.5f' % seconds
        if text:
            result += "   " + text
        print(result)

        self.pin_time()

        return seconds


time_logger = TimeLogger()
使用:

from .tests_time_logger import time_logger
class Tests(TestCase):
    def test_workflow(self):
    time_logger.pin_time()

    ... my functions here ...

    time_logger.log()

    ... other function(s) ...

    time_logger.log(text='Tests finished')
我在日志输出中有类似的内容

2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished
基于@Attaque great,我提出了一个简化版的日期时间差计算器:

seconds\u映射={
“y”:31536000,
“m”:2628002.88,#这是近似值,365/12;小心使用
“w”:604800,
“d”:86400,
“h”:3600,
"民":60,,
“s”:1,
“密耳”:0.001,
}
def get_持续时间(d1、d2、间隔,带_提醒=False):
如果有提醒:
返回divmod((d2-d1).total_seconds(),seconds_映射[间隔])
其他:
返回(d2-d1)。总秒数()/秒映射[间隔]
我对它进行了更改,以避免声明重复函数,删除了pretty print默认间隔,并添加了对毫秒、周和ISO月的支持(基于每个月等于
365/12
的假设,简单的月份只是近似值)

产生:

d1=datetime(2011,3,1,1,1,1000)
d2=日期时间(2011,4,1,1,1,1,12500)
打印(获取持续时间(d1,d2,'y',True))#=>(0.02678400.0015)
打印(获取持续时间(d1,d2,'m',True))#=>(1.050397.12149999989)
打印(获取持续时间(d1,d2,'w',True))#=>(4.0259200.0014999978)
打印(获取持续时间(d1,d2,'d',True))#=>(31.0,0.0014999997802078724)
打印(获取持续时间(d1,d2,'h',True))#=>(744.0,0.00149997802078724)
打印(获取持续时间(d1,d2,'min',True))#=>(44640.0,0.00149997802078724)
打印(获取持续时间(d1,d2,'s',True))#=>(2678400.0,0.00149997802078724)
打印(获取持续时间(d1,d2,'mil',True))#=>(2678400001.0,0.0004999972445247221)
打印(获取持续时间(d1,d2,'y',False))#=>0.08493150689687975
打印(获取持续时间(d1,d2,'m',False))#=>1.019176965856293
打印(获取持续时间(d1,d2,'w',False))#=>4.428571431051587
打印(获取持续时间(d1,d2,'d',False))#=>31.00000001736111
打印(获取持续时间(d1,d2,'h',False))#=>744.0000004166666
打印(获取持续时间(d1,d2,'min',False))#=>44640.0000249994
打印(获取持续时间(d1,d2,'s',False))#=>2678400.0015
打印(获取持续时间(d1,d2,'mil',False))#=>2678400001.4999995

要获得
小时
分钟
,您可以这样做

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m,s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60,m%60,s)

您可能会发现此快速代码段在不太长的时间间隔内很有用:

    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上测试,这将以秒为单位给出差值(然后除以60得到分钟):

导入时间
导入日期时间
t_start=datetime.datetime.now()
时间。睡眠(10)
t_end=datetime.datetime.now()
elapsedTime=(t_结束-t_开始)
打印(elapsedTime.total_seconds())