在python中以分钟为单位获取两个日期时间对象之间的差异

时间:2013-12-17 10:36:41

标签: python datetime timedelta

我有两个由strptime在Python中创建的日期时间对象:

date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")

end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")

日期时间对象已成功创建,因此我

>>>date
datetime.datetime(2013, 12, 18, 9, 30)
>>>end_date
datetime.datetime(2013, 12, 18, 10, 15)

我想计算两个日期时间不同的分钟数。我做了

diff = end_date - date   

我得到了

 datetime.timedelta(0)

所以它说它们是相同的日期?没有任何区别? 秒属性为零

>>>diff.seconds
0

如何才能使其发挥作用?

2 个答案:

答案 0 :(得分:7)

import datetime

date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")
print (end_date-date).total_seconds()

给出

2700.0

答案 1 :(得分:1)

有点奇怪,我得到了正确的结果:

>>> date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
>>> date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
>>> end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
>>> end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")
>>> diff = end_date - date
>>> diff
datetime.timedelta(0, 2700)
>>> diff.seconds
2700

这是整个代码吗?