Getting the difference between two dates or datetime objects in python is delightfully straightforward; you can just subtract them!
For date objects
from datetime import date
first_date = date(2021, 1, 1)
second_date = date(2022, 1, 1)
diff = second_date - first_date
# datetime.timedelta(days=365)
diff.days # 365The subtraction returns an object of class timedelta, which has a few handy properties like .seconds and .days. If using whole date objects however, only the .days property will matter. Since there’s no information about the time, seconds can’t be compared.
For datetime objects
The process of getting the diff is exactly the same, but the timedelta object will have a bit more information.
datetime1 = datetime.fromisoformat("2021-11-26T07:18:59")
datetime2 = datetime.fromisoformat("2022-09-13T13:52:19")
diff2 = datetime2 - datetime1
# datetime.timedelta(days=291, seconds=23600)Since these are datetime objects, the resulting timedelta also has a difference in seconds. This seconds difference is the difference in seconds between the two times only, not between the entire datetime; in this case, that’s the difference between 7:18:59 and 13:52:19. There is also a timedelta.total_seconds() method, which will get the entire difference between the two objects in seconds (and also works on date comparisons):
diff2.total_seconds() # 25166000.0It’s worth noting that timedelta only gives you days, seconds, and microseconds as options; if you want minutes or hours you have to multiply.
Related Links
- Calculate date difference in javascript – justinjoyce.dev
- Timedelta objects – python official docs
- fromisoformat – python official docs