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

Python test datetime object if it is in the past present or future

in python, if I have a date string in the following format yyyy-mm-dd, I would like to write a function to check if the date is in the past, present or future. However, I am having some trouble with this. I have written the following code…

from datetime import datetime

def check_date(date_string):
    this_date = datetime.strptime(date_string, '%Y-%m-%d')
    now = datetime.today()
    if this_date < now:
        print("the date is in the past")
    elif this_date > now:
        print("the day is in the future")
    else:
        print("the day is today")

however, when I tested this, it gives me…

>>check_date('2022-08-08')
the date is in the past
>>check_date('2022-10-10')
the day is in the future
>>check_date('2022-09-22') #this is todays date
the date is in the past

I’m not sure why it is giving this unexpected behaviour.
thanks

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

>Solution :

Try this!

from datetime import datetime

def check_date(date_string):
    this_date = datetime.strptime(date_string, '%Y-%m-%d').date()
    now = datetime.today().date()
    print(now, this_date)
    if this_date < now:
        print("the date is in the past")
    elif this_date > now:
        print("the day is in the future")
    else:
        print("the day is today")
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