Open In App

Pandas Convert Date (Datetime) To String Format

Last Updated : 04 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 Datetime to String

It is sometimes necessary to convert a date to a specific string format in data analysis.

  • While presenting and visualizing the data for good understanding, the datetime is converted to a specific string format.
  • When exporting the data into external applications, it is sometimes necessary to convert the datetime into a string format for the compatibility and consistency of the external application.
  • Converting datetime to strings allows us to perform various operations, such as concatenation, pattern matching, slicing and other string-based operations that can be used for data preprocessing.

What is a string?

A string is a sequence of alphabets, numbers, and other characters. It is a primitive data type in Python. It is immutable; once created, it cannot be changed. The number of characters in the string is known as the length of the string.

Now we will look into a few methods that help us convert datetime into a string representation.

1. astype() method:

Pandas provides us with astype() method to convert datetime column to string format. It is a method used to convert entire data type of a column from one type to another.

Python




# importing pandas as pd
import pandas as pd
 
# Create data with fields 'Date','Sales','Profit'
data = {
    'Date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
    'Sales': [101, 201, 301],
    'Profit': [909, 1809, 2709]
}
# Converting the data into dataframe by using pandas
df = pd.DataFrame(data)
print("Before conversion type:", type(df["Date"][0]))
 
# Using astype() method to convert 'Date' column values to Strings
df['Date'] = df['Date'].astype(str)
print("After conversion type:", type(df['Date'][0]))


Output:

Before conversion type: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
After conversion type: <class 'str'>

Datetime in pandas is represented by timestamp datatype. Now applying astype() method on the date column converts the date type into string. The type() method is used to know the data type of the entry. We can see the ‘Date’ column is converted into String representation from the timestamp datatype.

2. strftime() method:

The strftime() method, which formats a timestamp object according to a specified string format.

Python




#importing pandas as pd
import pandas as pd
 
data = {
    'Date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
    'Sales': [101, 201, 301],
    'Profit': [909, 1809, 2709]
}
 
df = pd.DataFrame(data)
 
#Using dt.strftime() method by passing the specific string format as an argument.
df['Date'] = df['Date'].dt.strftime('%d-%m-%Y')
print(df)
df.info()


Output:

         Date  Sales  Profit
0 01-01-2024 101 909
1 02-01-2024 201 1809
2 03-01-2024 301 2709
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 3 non-null object
1 Sales 3 non-null int64
2 Profit 3 non-null int64

Here, with dt.strftime() method we can pass a specific format as an argument in which we want to convert our date into. We use format specifiers like ‘%d’ ,‘%m’,‘%Y’ to pass the required format as an argument.

Conclusion:

In conclusion, we can convert date (datetime) to string format by using astype() and strftime() methods in pandas. The astype() method converts the entire date-time column into an object like String. It’s a simple and straightforward method but lacks the flexibility to customize the date format. While strftime() is a powerful method than astype() method. It takes the specific string format as an argument and offers us with the flexibility to convert into a specific string format.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads