I need to find how many calendar days elapsed sice given date. When I use the following, it gives me -1 even when the date is today:
>>> from datetime import datetime
>>> t = datetime.fromisoformat('2023-03-09 08:55:11')
>>> (t - datetime.today()).days
-1
Whereas the correct answer should be 0.
If I ask at 00:00:01, and the date was yesterday at 23:59:59, it should give me 1 day. But anything today should be 0.
How can I do that?
>Solution :
Convert both values to dates instead of datetimes.
It’s like comparing 0.9 to 1.1 and wanting the result to be 1. Converting them both to integers first would give 0 and 1 with a difference of 1.
So, compare dates, not datetimes…
from datetime import datetime, date
x = datetime.fromisoformat('2023-03-09 08:55:11')
y = datetime.fromisoformat('2023-03-10 07:00:00')
print((y - x).days)
print((y.date() - x.date()).days)
print()
y = datetime.fromisoformat('2023-03-10 09:00:00')
print((y - x).days)
print((y.date() - x.date()).days)
Demo : https://trinket.io/python3/013ac6c02a