Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How many calendar days elapsed since given date?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading