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
>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")