Click here to Skip to main content
15,935,728 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to check using Python if a random date provided is ambiguous or not.
For instance. 3/7/91. This could be March 7, XX91 or 3 July XX91. Thus, ambiguous.

My logic is - If the day & month both lie in the range of 1-12, then 'Day' & 'Month' are ambiguous. Also, if the 'Year' has only two digits, then its value is ambiguous.

This is what I've tried -->

Steps: 1) Mention the date
2) Split the date
3) Mention different combinations of date formats
4) If date format is the same but only with a difference in the separator &
the date & month have a value between 1-12 & the year contains only 2
digits, then the date is ambiguous, else, not.

What I have tried:

dmy_split=date.split('/, -')

date_formats = ['%d/%m/%Y','%m/%d/%Y','%Y/%m/%d','%d-%m-%Y','%m-%d-%Y', '%Y-%m-%d']

if (date_formats==date_formats[0] or date_formats==date_formats[3]):
  if (dmy_split[0] in range (1,13) and dmy_split[1] in range (1,13) or len(dmy_split[2])==2):
                                                                                   print("not ambiguous")

Issue: The result is always "not ambiguous". My logic seems right. Please let me know where I've gone wrong.
Updated 17-Aug-22 22:14pm

Your first if will always be false. You are comparing an array date_formats to a string date_formats[0]. You probably can do away with that line, since if both of the first two elements are in range, then you know its an ambiguous date.
Share this answer
Why are you not using the functions of the datetime module which will do the work much more efficiently? I gave you an answer to your previous question at Date formatting using Python[^]. And using the code in that answer will automatically throw an error if the date is not valid.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900