Home > Back-end >  How to detect the date format? (python)
How to detect the date format? (python)

Time:11-08

I have a Dataframe in python, with the data coming from a csv. In the column "Date" I have a date (:)) but I don't know the date format. How can I detect it?

e.g.: I can have 05/05/2022. this can be M/D/Y or D/M/Y. I can manually understand it by looking at other entries, but I wish I can do it automatically.

Is there a way to do so? thank you

datetime.strptime requires you to know the format. trying (try - exept)-commands isn't good since there are so many different format I can receive.

it would be nice to have something that recognizes the format...

CodePudding user response:

You can try the dateutil library. To deal with dates and also with the diversity of timezones people often use external libraries such as pytz or dateutil.

dateutil has a very powerful parser.

from dateutil.parser import parse

parse('05/05/2022')  # datetime.datetime(2022, 5, 5, 0, 0)
parse('2022-05-05')  # datetime.datetime(2022, 5, 5, 0, 0)

CodePudding user response:

Use the isinstance built-in function to check if a variable is a datetime object in Python, e.g. if isinstance(today, datetime): . The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class. Copied!20-Apr-2022

check out here

https://www.folkstalk.com/2022/10/python-check-if-string-is-date-format-with-code-examples.html

  • Related