3.1 C
London
Friday, December 20, 2024
HomePandas in PythonGeneral Functions in PythonHow to Convert DateTime to String in Pandas (With Examples)

How to Convert DateTime to String in Pandas (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to convert a column from DateTime to string in pandas:

df['column_name'].dt.strftime('%Y-%m-%d')

The following example shows how to use this syntax in practice.

Example: Convert DateTime to String in Pandas

Suppose we have the following pandas DataFrame that shows the sales made by some store on four different days:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'day': pd.to_datetime(pd.Series(['20210101', '20210105',
                                                    '20210106', '20210109'])),
                   'sales': [1440, 1845, 2484, 2290]})

#view DataFrame
df

	       day     sales
0	2021-01-01	1440
1	2021-01-05	1845
2	2021-01-06	2484
3	2021-01-09	2290

We can use the dtypes function to view the data type of each column in the DataFrame:

#view data type of each column
df.dtypes

day      datetime64[ns]
sales             int64
dtype: object

We can see that the “day” column has a DateTime class.

To convert “day” into a string, we can use the following syntax:

#convert 'day' column to string
df['day'] = df['day'].dt.strftime('%Y-%m-%d')

#view updated DataFrame
df

	       day     sales
0	2021-01-01	1440
1	2021-01-05	1845
2	2021-01-06	2484
3	2021-01-09	2290

We can use the dtypes function again to verify that the “day” column is now a string:

#view data type of each column
df.dtypes

day      object
sales     int64
dtype: object

Note: You can find the complete documentation for the dt.strftime() function here.

Additional Resources

The following tutorials explain how to perform other common conversions in Python:

How to Convert Datetime to Date in Pandas
How to Convert Columns to DateTime in Pandas
How to Convert Timestamp to Datetime in Pandas

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories