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

How do I find the time difference between two datetime objects in python?

如何分辨两个datetime对象之间的时间差(分钟)?


1
2
3
4
5
6
7
>>> 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


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

参考:http://docs.python.org/2/library/datetime.html datetime.timedelta.total_seconds

1
2
3
4
5
6
7
8
9
>>> 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


使用日期时间示例

1
2
3
4
5
>>> 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

持续时间(年)

1
>>> years = divmod(duration_in_s, 31556926)[0]    # Seconds in a year=31556926.

持续时间(天)

1
2
>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400

持续时间(小时)

1
>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600

持续时间(分钟)

1
>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60

持续时间(秒)

1
2
>>> seconds = duration.seconds                    # Build-in datetime function
>>> seconds = duration_in_s

持续时间(微秒)

1
>>> microseconds = duration.microseconds          # Build-in datetime function

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

1
2
3
4
5
>>> 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]))

或者简单地说:

1
>>> print(now - then)

从另一个中减去一个。你得到一个有差别的timedelta对象。

1
2
3
4
5
>>> 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.daysdd.secondsdd.microseconds转换为分钟。


如果ab是datetime对象,那么在python 3中查找它们之间的时间差:

1
2
3
4
from datetime import timedelta

time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)

在早期的python版本上:

1
time_difference_in_minutes = time_difference.total_seconds() / 60

如果ab是幼稚的日期时间对象,如datetime.now()返回的日期时间对象,则如果这些对象表示具有不同的UTC偏移量的本地时间(如DST转换前后或过去/未来日期),则结果可能是错误的。更多详细信息:查找日期时间-python之间是否已经过了24小时。

要获得可靠的结果,请使用支持UTC时间或时区的日期时间对象。


使用DIVMOD:

1
2
3
4
5
6
7
8
9
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)


以下是获取两个datetime.datetime对象之间经过的小时数的方法:

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


只需查找天数:TimeDelta有一个"days"属性。您可以简单地查询它。

1
2
3
4
5
6
7
8
>>>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()根据格式解析表示时间的字符串。

1
2
3
4
5
6
7
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: 0.518000


我用这样的东西:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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之间的差异。

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


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

1
2
3
4
5
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)

所以以分钟为单位得到输出。

谢谢


这是我使用mktime的方法。

1
2
3
4
5
6
7
8
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