How to tell if two dates are adjacent using python

Python Code

from datetime import datetime


def are_days_ajacent(day1: str, day2: str) -> bool:
    day1 = datetime.strptime(str(day1), '%Y-%m-%d')
    day2 = datetime.strptime(str(day2), '%Y-%m-%d')
    return abs((day1 - day2).days) == 1


print(are_days_ajacent('2022-05-30', '2022-06-01'))
print(are_days_ajacent('2022-05-30', '2022-05-31'))
print(are_days_ajacent('2022-05-31', '2022-05-30'))

Code Output:

False
True
True

Note:

  • Modify the date format %Y-%m-%d as your wish.
  • day1 - day2 returns a timedelta object. Its days property can be positive or negative.
Posted on 2022-06-17