Convert “unknown format” strings to datetime objects in Python
In this article, we are going to see how to convert the “Unknown Format” string to the DateTime object in Python.
Suppose, there are two strings containing dates in an unknown format and that format we don’t know. Here all we know is that both strings contain valid date-time expressions. By using the dateutil module containing a date parser that can parse date strings in many formats.
Let’s see some examples that illustrate this conversion in many ways:
Example 1: Convert “unknown format” strings to datetime objects
In the below example, the specified unknown format of date string “19750503T080120” is being parsed into a valid known format of the DateTime object.
Example 2: Convert current date and time to datetime objects
In the below example, the current date and time have been parsed into datetime object.
2021-08-20T13:35:23.829488 2021-08-20 13:35:23.829488
Sometimes the DateTime strings can be ambiguous like 01-02-2003 could mean January 2 or February 1. To remove this ambiguity we have two parameters like dayfirst and yearfirst that are illustrated in the below examples.
Example 3: Convert specific unknown format to datetime objects
In the below example, the specified datetime is “10-09-2021”. The parse() has used the parameter dayfirst as True and returns the output as “2021-09-10 00:00:00” i.e 9th October of the 2021 year.