Click here to Skip to main content
15,847,750 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm writing a program that collects a date, checks if the date matches any of the mentioned date formats. If there's a match 'True' is returned, else, 'False'.


Issue: Why isn't my "any()" working as expected?

What I have tried:

Here's my code --->

Python
from datetime import datetime

x = "24-3-2012"
date_formats = ['%d/%m/%Y','%m/%d/%Y','%Y/%m/%d','%d-%m-%Y','%m-%d-%Y', '%Y-%m-%d']
for i in date_formats:
    try:
        d = datetime.strptime(x, i)
        print(any(x))
        
    except ValueError:
        print("False")


Expected output --> True

Observed output --> False False False True False False
Posted
Updated 17-Aug-22 1:43am
Comments
Richard Deeming 17-Aug-22 6:25am    
Your function clearly doesn't behave in the way you describe. Apart from anything else, it will print "False" for every format that the input doesn't match, even if it does match one of the other formats.

And any(x) isn't doing what you think it's doing either:
Built-in Functions — Python 3.10.6 documentation[^]
Apoorva 2022 17-Aug-22 6:39am    
I've mentioned the output I received.
For instance - x = "2019-8-30" gives
False
False
False
False
False
True

1 solution

You need to print the details when you find a valid format, and also break out of the loop. If the loop completes without finding one, the you can print the exception message. So your code should be:
Python
for i in date_formats:
    try:
        d = datetime.strptime(x, i)
        print(F"{x = }, {i = }") # print the date and the found format
        break                    # break out of the loop, no more searching is needed
    except ValueError:
        pass                     # keep going to test all formats

else:                            # this else belongs to the for statement
    print("False")               # all formats have been tried but none match
 
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