Click here to Skip to main content
15,881,690 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My program converts a date to the 'dmy' format & checks if it's 'Ambiguous', 'True' (no ambiguity), or 'False'. I have used 'Date Parser' in this program .


Code Explanation:
1. Take a date
2. Convert it into the 'dmy' format using 'Date Parser'.
3. Split the date
4. If the first 2 parts(d & m) are in the same range (1-12) or when the length of 'Y' is 2 , then the date is ambiguous. Else, the date is true.
5. If the date is invalid, then 'False'.

My output for the test cases is supposed to be-->
False
Ambiguous
True

Observed output-->
False
Ambiguous
Ambiguous

My doubt -->
I'm getting the right output for the last test case when I change len(dmy_split[2])==2 to len(dmy_split[2])==0. I'm curious to know why '0' is working well for my code.

What I have tried:

Python
<pre>from dateutil.parser import parse
import re

def date_fun(date):
  
  try:
    dmy_split=re.split('[- / ]', date)
    dt = parse(date)
    dt.strftime('%d/%m/%Y')
   
    if (eval(dmy_split[0]) >=1 and eval(dmy_split[0]) <=12 and eval(dmy_split[1]) >=1 and eval(dmy_split[1]) <=12 or len(dmy_split[2])==2):
                                                 print("ambiguous")              # Format matched   
    else:
                                                     print("True")
  except ValueError:        # If match not found keep searching
                                                     #pass     
                                                     print("False")                                               

date_fun("abc")
date_fun("12/1/91")
date_fun("2002-09-18")
Posted
Updated 25-Aug-22 22:24pm
Comments
Richard MacCutchan 26-Aug-22 4:15am    
Use the debugger, or add some print statements, to check what values are created in the first three lines of the try block.

1 solution

Well, I just tried that and the output is:
['2002', '09', '18']
2002-09-18 00:00:00
ambiguous

Which obviously shows that the date is not in the format that you assume. So if we look back at the line:
Python
dt.strftime('%d/%m/%Y')

we can see that it does not do anything useful.
So change that code to:
Python
dmy_split=re.split('[- / ]', date)
print(dmy_split)
dt = parse(date)
print(dt)
dt = dt.strftime('%d/%m/%Y')
print(dt)
dmy_split=re.split('[- / ]', dt)
print(dmy_split)

I have deliberately left the print statements so you can actually see what happens, and also how to do your own debugging.
 
Share this answer
 
Comments
CPallini 26-Aug-22 4:47am    
5.
Richard MacCutchan 26-Aug-22 4:56am    
Thanks.

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