0
votes

Python datetime objects require a year, however I would just like to write a function that outputs the differences in dates between two day-months ignoring year. Meaning the output range of this function is [-182, 183], since the calculations should "wrap around" the year.

Example: Goal date: 1st Jan Guess: 31st Dec Result: -1

Goal date: 1st Jan Guess: 2nd Jan Result: +1

def date_diff(goal, guess):
    #goal and guess are in the format "%m-%d"
    
    goal_date = datetime.strptime(goal + "-2020", "%m-%d-%Y")
    goal_date1 = datetime.strptime(goal + "-2021", "%m-%d-%Y")
    guess_date = datetime.strptime(guess + "-2020", "%m-%d-%Y")
    guess_date1 = datetime.strptime(guess + "-2021", "%m-%d-%Y")
    
    r1 = goal_date - guess_date
    r1 = r1.days
    r3 = goal_date1 - guess_date
    r3 = r3.days
    r2 = guess_date1 - goal_date
    r2 = r2.days
    r4 = guess_date - goal_date
    r4 = r4.days

    r = ((r1, math.copysign(1, r1)), (r2, math.copysign(1, r2)),(r3, math.copysign(1, r2)),(r4, math.copysign(1, r4)))
    
    #idea here was the find min of index 0 of each tuple then restore the sign, but i think i'm missing some combinations
    smallest =  min(r, key = lambda x:abs(x[0]))
    return smallest[0]*smallest[1]
1
What have you tried so far? And BTW not every year has 365 days.Klaus D.
Tried appending a random year onto each guess, but that would require me to try two years for each goal and guess, and it didn't feel as elegantzhao
Show us some code!Klaus D.
updated with code, i'm alright with ignoring leap yearszhao
Are you not considering leap year? [-182, 183] means total 366 days right and this is for 2020? For 2021 it will be [-182,182] right?Epsi95

1 Answers

0
votes

You can take the minimum (absolute) difference with the second date at the previous, same and next year of the first date

For example :

from datetime import date
def dateDelta(d1,d2):
    return min(((date(d1.year+i,d2.month,d2.day)-d1).days 
                 for i in (-1,0,1)),key=abs)


d1 = date(2002,10,15)
d2 = date(2002,2,3)

print(dateDelta(d1,d2)) # 111
print(dateDelta(d2,d1)) # -111

Note that you may get varying results depending on the reference year you chose. To avoid interference from leap years, select a non-leap year for d1 that is neither before nor after a leap year (e.g. 2002, or any year mod 4 == 2)