在Python中查找两个日期之间的中点日期

时间:2014-08-24 15:42:18

标签: python date datetime

给定日期:

my_guess = '2014-11-30'
their_guess = '2017-08-30'

如何拆分日期之间的差异,返回正确的日历日期?

2 个答案:

答案 0 :(得分:23)

一种方法是使用datetime。找出两个日期之间的差异,将其减半,并在较早的日期添加:

>>> from datetime import datetime
>>> a = datetime(2014, 11, 30)
>>> b = datetime(2017, 8 ,30)
>>> a + (b - a)/2
2016-04-15 00:00:00

答案 1 :(得分:3)

from datetime import datetime
d1 = datetime.strptime(my_guess,"%Y-%m-%d")
d2 = datetime.strptime(their_guess,"%Y-%m-%d")
print d1.date() + (d2-d1) / 2 # first date plus the midpoint of the difference between d1 and d2  
2016-04-15