Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get datetime format from string python

In Python there are multiple DateTime parser’s which can parse a date string automatically without proving the datetime format. My problem is that i dont need to cast the datetime, but i need just the datetime format.

Example:
From "2021-01-01" i want somethings like "%Y-%m-%d" or "yyyy-MM-dd".

My only idea was to try casting with different formats and get the successful one, but i dont want to list every possible formats.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m working with pandas so i can use both methods that works with series or just string DateTime parser.

Any ideas?

>Solution :

In pandas, this is achieved by pandas._libs.tslibs.parsing.guess_datetime_format

from pandas._libs.tslibs.parsing import guess_datetime_format

guess_datetime_format('2021-01-01')

# '%Y-%m-%d'

As there will always be an ambiguity on the day/month, you can specify the dayfirst case:

guess_datetime_format('2021-01-01', dayfirst=True)
# '%Y-%d-%m'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading