0

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...

Update: Thank you for the first answers, but the output I would like to have is THE FORMAT of the date that is used in the column. Knowing also the fact that the format is unique within each column

4
  • Perhaps the issue is with the source data provider. Is it possible to request clean data from the provider; or for the provider to sanitise their data first? Commented Nov 7, 2022 at 15:07
  • Yes, the issue is EXACTLY the provider, who is incompetent :) I cannot trust him at all, nor replace him. Hence my problem :) Commented Nov 8, 2022 at 16:21
  • Do you have an example ? Something like that ? Input "08/11/2022" -> Output "%d/%m/%Y" Commented Nov 8, 2022 at 16:45
  • Precisely liker that. Usually the inputs can be 1/12/2022 or 12/1/2022 or 1-12-2022 or 12-1-2022. I would like an output like "%d%m%Y" or "%m%d%Y" etc... Commented Nov 10, 2022 at 8:13

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, I edited the question cause it was not clear.
0

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

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.