Convert “unknown format” strings to datetime objects in Python
Last Updated :
31 Aug, 2021
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.
Python3
import dateutil.parser as parser
date_string = "19750503T080120"
date_time = parser.parse(date_string)
print (date_time)
|
Output:
1975-05-03 08:01:20
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.
Python3
import dateutil.parser as parser
import datetime as dt
now = dt.datetime.now()
print (now.isoformat())
print (parser.parse(now.isoformat()))
|
Output:
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.
Python3
import dateutil.parser as parser
B = parser.parse( "10-09-2021" , dayfirst = True )
print (B)
|
Output:
2021-09-10 00:00:00
Please Login to comment...