I am currently trying to construct a function that takes a date string and returns the number of days from that date until now. It will return 0 if it detects that the format is wrong, with the input date string format being Day/Month/Year (e.g. 12/3/21). The number should be negative if it is a past date (e.g. today is 14/3/21, the input date is 3/3/21, the function should return -11). This is my code so far but it keeps returning 0:
from datetime import datetime from datetime import date def convert_date(input_date): try: current_date = date.today() d1 = datetime.strptime(input_date, '%d/%m/%y') d2 = datetime.strptime(current_date, '%d/%m/%y') delta = d1 - d2 return delta.day except: return 0
I am very unsure on what I have done wrong, as I have done a lot of research but have not found a solution. Hopefully someone can provide further clarification, thanks
(Also i am using the Datetime package)
Advertisement
Answer
These are basics and you need to understand datetime module well. Hope this solves your problem.
from datetime import datetime def convert_date(input_date): try: current_date = datetime.today() d1 = datetime.strptime(input_date, '%d/%m/%y') delta = d1 - current_date return delta.days except ValueError: return 0