How many calendar days elapsed since given date?
Question:
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?
Answers:
The reason you are getting a negative result is that you are subtracting the current date from a future date. You can use math.abs, or just:
t= datetime.fromisoformat('2023-03-01')
elapsed_days = (datetime.today() - t).days
print(elapsed_days)
from datetime import datetime, date
given_date = datetime.fromisoformat('2023-03-09 08:55:11')
today = datetime.now().date() # get current date without time
elapsed_days = (today - given_date.date()).days
print(elapsed_days)
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)
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?
The reason you are getting a negative result is that you are subtracting the current date from a future date. You can use math.abs, or just:
t= datetime.fromisoformat('2023-03-01')
elapsed_days = (datetime.today() - t).days
print(elapsed_days)
from datetime import datetime, date
given_date = datetime.fromisoformat('2023-03-09 08:55:11')
today = datetime.now().date() # get current date without time
elapsed_days = (today - given_date.date()).days
print(elapsed_days)
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)