Change String To Date In Pandas Dataframe
Last Updated :
17 Mar, 2025
Working with date and time data in a Pandas DataFrame is common, but sometimes dates are stored as strings and need to be converted into proper date formats for analysis and visualization. In this article, we will explore multiple methods to convert string data to date format in a Pandas DataFrame.
Using pandas.to_datetime()
This is the most commonly used method to convert string dates into datetime64[ns] format. It automatically detects and converts various date formats, making it efficient for handling standard date strings.
Python
import pandas as pd
data = {
'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],
'Values': [100, 200, 300]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Using pandas.to_datetime()
df['Date'] = pd.to_datetime(df['Date'])
print(df.dtypes)
OutputDate datetime64[ns]
Values int64
dtype: object
Explanation: This code creates a DataFrame from a dictionary with date strings and numerical values, then converts the 'Date' column to datetime64[ns] using pandas.to_datetime() for proper date handling.
Using datetime.strptime()
This method is useful when dealing with custom date formats. The strptime() function from Python’s datetime module allows precise control over how dates are parsed by specifying a format string.
Python
import pandas as pd
from datetime import datetime
data = {
'Date': ['01-01-2022', '02-01-2022', '03-01-2022'],
'Values': [100, 200, 300]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Custom format conversion
df['Date'] = df['Date'].apply(lambda x: datetime.strptime(x, '%d-%m-%Y'))
print("\nAfter converting")
print(df.dtypes)
OutputAfter converting
Date datetime64[ns]
Values int64
dtype: object
Explanation: This code creates a DataFrame with date strings in DD-MM-YYYY format and numerical values. It uses apply() with datetime.strptime() to convert each date string into a datetime object for proper date handling.
Using pd.Series.dt.strftime()
Once a column is converted to a datetime64 type, strftime() helps format it into a specific date string format (e.g., DD-MM-YYYY). This method is useful for displaying dates in a customized way.
Python
import pandas as pd
data = {
'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],
'Values': [100, 200, 300]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Convert Date column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Convert Date column to a different format
df['Formatted_Date'] = df['Date'].dt.strftime('%d-%m-%Y')
print(df)
Output Date Values Formatted_Date
0 2022-01-01 100 01-01-2022
1 2022-01-02 200 02-01-2022
2 2022-01-03 300 03-01-2022
Explanation:The code converts date strings to datetime using pd.to_datetime() and formats them as DD-MM-YYYY using .dt.strftime(), storing the result in 'Formatted_Date'.
Using astype()
astype() method allows direct conversion of a column’s data type. When applied to a date column, it converts strings to datetime64[ns]. However, it requires that all values follow a uniform date format.
Python
import pandas as pd
data = {
'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],
'Values': [100, 200, 300]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Using DataFrame.astype()
df['Date'] = df['Date'].astype('datetime64[ns]')
print("\nAfter converting")
print(df.dtypes)
OutputAfter converting
Date datetime64[ns]
Values int64
dtype: object
Explanation: This code creates a DataFrame with date strings and numerical values, then uses astype('datetime64[ns]') to convert the 'Date' column into a datetime format, enabling efficient date-based operations.
Handling different date formats in column
When a column contains multiple date formats, pandas.to_datetime() can be used with errors='coerce', which replaces invalid date formats with NaT (Not a Time). This ensures the dataset remains clean and properly formatted.
Python
import pandas as pd
data = {
'Date': ['2022-01-01', '01-02-2022', 'March 3, 2022', 'Invalid Date'],
'Values': [100, 200, 300, 400]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Handling multiple date formats
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
print("\nAfter converting")
print(df)
OutputAfter converting
Date Values
0 2022-01-01 100
1 NaT 200
2 NaT 300
3 NaT 400
Explanation: This code converts various date formats in the 'Date' column to datetime using pd.to_datetime(), handling errors with errors='coerce', which replaces invalid dates with NaT.
Similar Reads
How to Change Pandas Dataframe Datetime to Time The DatetimeIndex contains datetime64[ns] data type, which represents timestamps with nanosecond precision. In many cases, we may just want to extract the time component from a Pandas Datetime column or index. Let's discuss easy ways to convert the Datetime to Time data while preserving all the time
2 min read
How to Sort a Pandas DataFrame by Date? In the real world, we can come across datasets of any form that may include the date inside them too. These datasets can be present in any file format like .CSV, .xlsx, .txt, etc. To load this data inside Python, we use a library named Pandas which provides us a plethora of functions and methods to
3 min read
Pandas Convert Date (Datetime) To String Format We are given a column containing datetime values in a pandas DataFrame and our task is to convert these datetime objects into string format. This conversion is useful for visualizing data, exporting it to external applications, or performing string operations. For example, if we have this input:a =
4 min read
How to Convert Float to Datetime in Pandas DataFrame? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax:
3 min read
How to Group Pandas DataFrame By Date and Time ? In this article, we will discuss how to group by a dataframe on the basis of date and time in Pandas. We will see the way to group a timeseries dataframe by Year, Month, days, etc. Additionally, we'll also see the way to groupby time objects like minutes. Pandas GroupBy allows us to specify a groupb
3 min read
How to Convert Integer to Datetime in Pandas DataFrame? Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of  pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check
2 min read
Convert a series of date strings to a time series in Pandas Dataframe During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date str
3 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
1 min read
How to Convert Datetime to Date in Pandas ? DateTime is a collection of dates and times in the format of "yyyy-mm-dd HH:MM:SS" where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time. In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime us
4 min read
Convert column type from string to datetime format in Pandas dataframe To perform time-series operations, dates should be in the correct format. Let's learn how to convert a Pandas DataFrame column of strings to datetime format. Pandas Convert Column To DateTime using pd.to_datetime()pd.to_datetime() function in Pandas is the most effective way to handle this conversio
4 min read