22

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?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
blacksheep9000
  • 383
  • 2
  • 3
  • 6

2 Answers2

43

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
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • This not only works with `datetime` objects, but with `date` objects as well (tested in Python 3.5) – phoibos Jun 15 '17 at 21:02
  • 4
    Just an FYI, know it's been 6 years, but this is not working as expected in Python 3.9 - the result of `a + (b - a)/2` is just the value of a for me. – ThePartyTurtle Nov 05 '21 at 15:28
  • 1
    I had the error: `TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'` any idea why? – J Agustin Barrachina Feb 24 '23 at 12:57
  • Ok, I said... `a + (b - a)/2` is the same as `(a + b) / 2`... well it is not... – J Agustin Barrachina Feb 24 '23 at 13:05
  • 3
    @AgustinBarrachina: Python doesn't allow you to add `datetime` objects: you need `datetime + timedelta` (subtracting `datetime` objects gives you a `timedelta` object). – Alex Riley Feb 24 '23 at 22:11
  • @ThePartyTurtle: this method still works for me (I tried in Python 3.10): if you have an example where it produces an incorrect result please let me know values for `a` and `b` and I will investigate. – Alex Riley Feb 24 '23 at 22:13
5
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 
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321