Skip to content Skip to sidebar Skip to footer

Finding Mid-point Date Between Two Dates In Python

Given dates: my_guess = '2014-11-30' their_guess = '2017-08-30' How do I split the delta between the dates, returning the correct calendar date?

Solution 1:

One way would be to use datetime. Find the difference between two dates, halve it, and add it on the earlier date:

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

Solution 2:

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 

Post a Comment for "Finding Mid-point Date Between Two Dates In Python"