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 Convert String to Float in Pandas DataFrame
Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs. In this article, we'll look at different ways to convert a string to a float in DataFrame. Creating Sample D
4 min read
How to Convert Floats to Strings in Pandas DataFrame?
In this post, we'll see different ways to Convert Floats to Strings 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 String, String to Integer, Float to String, etc. There are three methods
4 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
Python | Pandas dataframe.pct_change()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.pct_change() function calculates the percentage change between the cu
2 min read
Pandas Convert Date (Datetime) To String Format
Datetime is a data type in Pandas that provides a standardized way to represent and display dates and times in a human-readable format. It allows customization of output, such as displaying months, days, and years, offering flexibility in presenting temporal information. Necessity to convert Datetim
5 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
Replace Characters in Strings in Pandas DataFrame
In this article, we are going to see how to replace characters in strings in pandas dataframe using Python. We can replace characters using str.replace() method is basically replacing an existing string or character in a string with a new one. we can replace characters in strings is for the entire d
3 min read
How to rename columns in Pandas DataFrame
In this article, we will see how to rename column in Pandas DataFrame. The simplest way to rename columns in a Pandas DataFrame is to use the rename() function. This method allows renaming specific columns by passing a dictionary, where keys are the old column names and values are the new column nam
4 min read