I am trying to run this code
def main():
month_name = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
while True:
try:
date = dated(input("Date: "))
month, day, year = date
if int(day) <= 31:
if 1<= int(month) <= 12:
month = month.zfill(2)
print(f"{year}-{month}-{day}")
break
else:
if int(day) <= 31:
for i in range(len(month_name)):
if month_name[i] == month:
month = i+1
month = month.zfill(2)
print(f"{year}-{month}-{day}")
break
else:
return ValueError
except ValueError:
continue
def dated(s):
if "/" in s:
s = s.split("/")
if len(s[1]) == 1:
s[1] = s[1].zfill(2)
return s
else:
return s
else:
s = s.split(" ")
s[1] = s[1].replace(",","")
if len(s[1])== 1:
s[1] = s[1].zfill(2)
return s
else:
return s
if __name__ == "__main__":
main()
The purpose of this code is if an user provides input of date in mmddyyyy format specifically like 10/08/1991 or October 8, 1991 it will display the date in yyyymmdd format like 1991-10-08. On executing this code for date format 10/08/1991, if the input is in range it works otherwise also the loop breaks but if the input is in second format October 8, 1991 the code is not working on trying to debug I found that for
while True:
try:
date = dated(input("Date: "))
month, day, year = date
if int(day) <= 31:
if 1<= int(month) <= 12:
month = month.zfill(2)
print(f"{year}-{month}-{day}")
break
the code is running fine but after that for
else:
if int(day) <= 31:
for i in range(len(month_name)):
if month_name[i] == month:
month = i+1
month = month.zfill(2)
print(f"{year}-{month}-{day}")
break
else:
return ValueError
the code is not working. if I input October 10, 1991 the code will jump straight to
except ValueError:
continue
and I input 15/10/1991 the code breaks out. The problem is coming only in if else part of main function, dated function is working perfectly fine.
Here is a much cleaner way of achieving the same using the built-in datetime module.
from datetime import datetime
def convert_date_to_yyyymmdd(date_str):
try:
# Try to parse the date in mm/dd/yyyy format
date_obj = datetime.strptime(date_str, '%m/%d/%Y')
except ValueError:
try:
# Try to parse the date in Month dd, yyyy format
date_obj = datetime.strptime(date_str, '%B %d, %Y')
except ValueError:
# If both formats fail, raise an error
raise ValueError("The date format is not recognized. Please use mm/dd/yyyy or Month dd, yyyy format.")
# Convert the datetime object to the desired string format
return date_obj.strftime('%Y-%m-%d')
# Example usage:
date1 = "10/08/1991"
date2 = "October 8, 1991"
print(convert_date_to_yyyymmdd(date1)) # Output: 1991-10-08
print(convert_date_to_yyyymmdd(date2)) # Output: 1991-10-08
which returns:
1991-10-08
1991-10-08
Note that the datetime module has a multitude of other useful features too which will save you from reinventing the wheel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With