pandas to_datetime mixed format
The pandas.to_datetime()
function in pandas library allows you to convert a string or a series of strings into a datetime object in pandas. It can handle a variety of date and time string formats, including mixed formats.
To convert strings with mixed formats into datetime objects, you need to provide a format argument to the pandas.to_datetime()
function. The format argument is a string that specifies the expected format of the datetime string.
When dealing with mixed formats, you can use a combination of different format codes. Some commonly used format codes are:
%Y
– 4 digit year%m
– 2 digit month (01 to 12)%d
– 2 digit day (01 to 31)%H
– 2 digit hour in 24-hour format (00 to 23)%M
– 2 digit minute (00 to 59)%S
– 2 digit second (00 to 59)%f
– microsecond (000000 to 999999)
Examples:
Let’s consider some examples to understand how pandas.to_datetime()
handles mixed formats:
# Importing pandas library
import pandas as pd
# Creating a list of strings with mixed date formats
date_strings = ['2021-01-01', '2021/01/02', '01-03-2021', '20210304']
# Converting the list of strings to datetime objects
datetime_objects = pd.to_datetime(date_strings, format='%Y-%m-%d')
# Printing the datetime objects
print(datetime_objects)
In this example, we have a list of date strings with different formats. We provide the format='%Y-%m-%d'
argument to pandas.to_datetime()
function to specify the expected format. The function then converts the strings into datetime objects and returns a pandas Series of datetime objects. The output will be:
0 2021-01-01
1 2021-01-02
2 2021-01-03
3 2021-03-04
dtype: datetime64[ns]
The datetime objects are successfully created with the specified format.