Open In App

Convert “unknown format” strings to datetime objects in Python

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to illustrate the conversion of
# "unknown format" strings to DateTime objects
  
# Importing parser from the dateutil.parser
import dateutil.parser as parser
  
# Initializing an unknown format date string
date_string = "19750503T080120"
  
# Calling the parser to parse the above
# specified unformatted date string
# into a datetime objects
date_time = parser.parse(date_string)
  
# Printing the converted datetime object
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




# Python3 code to illustrate the conversion of
# "unknown format" strings to DateTime objects
  
# Importing parser from the dateutil.parser and
# dt from datetime module
import dateutil.parser as parser
import datetime as dt
  
# Calling the now() function to
# return the current datetime
now = dt.datetime.now()
  
# Calling the isoformat() to return the
# current datetime in isoformat and print it
print(now.isoformat())
  
# Now calling the parser to parse the
# above returned isoformat datetime into
# a valid known format of datetime object
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




# Python3 code to illustrate the conversion of
# "unknown format" strings to DateTime objects
  
# Importing parser from the dateutil.parser
import dateutil.parser as parser
  
# Now parsing the "10-09-2021" datetime with
# dayfirst parameter
B = parser.parse("10-09-2021", dayfirst = True)
  
# Printing the parsed datetime
print(B)


Output:

2021-09-10 00:00:00


Previous Article
Next Article

Similar Reads

How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Convert the column type from string to datetime format in Pandas dataframe
While working with data in Pandas, it is not an unusual thing to encounter time series data, and we know Pandas is a very useful tool for working with time-series data in Python.Let's see how we can convert a dataframe column of strings (in dd/mm/yyyy format) to datetime format. We cannot perform any time series-based operation on the dates if they
4 min read
Pandas Series dt.to_period() Method | Convert DateTime to Period Format
The Pandas dt.to_period() method converts the underlying data of the given Series object to PeriodArray/Index at a particular frequency. It is used to convert a DateTime series to a period series with a specific frequency, such as daily, monthly, quarterly, or yearly periods. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '201
2 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Pandas Series dt.to_pydatetime | Return Python DateTime Objects
Pandas dt.to_pydatetime() method returns the data as an array of native Python DateTime objects. Timezone information is retained if present. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
How to change the Pandas datetime format in Python?
Prerequisites: Pandas The date-time default format is "YYYY-MM-DD". Hence, December 8, 2020, in the date format will be presented as "2020-12-08". The datetime format can be changed and by changing we mean changing the sequence and style of the format. Function used strftime() can change the date format in python. Syntax: strftime(format) Where, fo
1 min read
Python | Remove item from dictionary when key is unknown
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
6 min read
Practice Tags :
three90RightbarBannerImg