0

I'm getting the date in a string and it's not always same format, is there a way to detect what format is that date for example:

If data comes like this 2023-12-03 I want to somehow get output like this "%Y-%m-%d", so I know which format is using. This is just an example format date in the string can come also like this 13/02/2023 and the format would be "%d/%m/%Y"

GomuGomu
  • 304
  • 2
  • 9
  • 2
    Is there a limited number of formats such that you could just try all the possibilities and take the one that yields the most valid-looking answer? Or are you trying to build a system that will handle unknown unknowns? – Samwise Mar 03 '23 at 16:57
  • Do you want to _obtain the format string_, or do you want to _parse the date regardless of the format_ as the answers have shown? – Pranav Hosangadi Mar 03 '23 at 19:15

1 Answers1

-1

You can use dateutil to parse it

from dateutil.parser import parse

date_string = "2023-12-03"
date = parse(date_string)

print(date.strftime("%Y-%m-%d"))

This code will output "2023-12-03" because the input date string is already in the format "%Y-%m-%d".

If the input date string is in a different format, dateutil will try to automatically detect the format and parse the date correctly. For example, if the date string is "12/03/2023", the following code will output "2023-12-03"

Jan
  • 302
  • 3
  • 5