简体   繁体   中英

Difference between two dates ignoring year

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]

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 (eg 2002, or any year mod 4 == 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM