0

I need help in checking if the given date is present in the date format of a list. I have a list of date formats. I want to check if a given date is present in that date format. How do I do that? However, I tried doing it though getting an error.

My code:

x = "03-24-2019"
Date = ['%Y/%m/%d','%Y-%m-%d','%Y%m%d','%m/%d/%Y','%m-%d-%Y']
if x in any(Date):
    print(Date)
else:
    print('no')

Error message:

TypeError: argument of type 'bool' is not iterable

Execpted Output:

%m-%d-%Y
3
  • 2
    any(Date) is just True Commented Mar 12, 2021 at 16:27
  • @TrentonMcKinney oh, How do I match it then? Commented Mar 12, 2021 at 16:29
  • 1
    Write a parser. Based on number range and number separators get a format. Then check that string format in the list. Commented Mar 12, 2021 at 16:30

1 Answer 1

2

The below should work.

The idea is to loop over formats and try to call strptime

from datetime import datetime

x = "03-24-2019"
date_formats = ['%Y/%m/%d', '%Y-%m-%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y']
for date_format in date_formats:
    try:
        d = datetime.strptime(x, date_format)
        print(date_format)
        break
    except ValueError as e:
        pass

output

%m-%d-%Y
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.