Dates and times can be hard to work with, especially when it comes to putting them in the right format. Pandas is a library for analyzing data. It has several ways to handle and format date and time data. Changing the date-time format is a common task. We’ll look at how to change the date-time format in Pandas in this article.
First, let’s make an example date-time dataframe:
import pandas as pd import numpy as np date_rng = pd.date_range(start='1/1/2020', end='1/10/2020', freq='H') df = pd.DataFrame(date_rng, columns=['date']) df['data'] = np.random.randint(0,100,size=(len(date_rng)))
This is how the sample ‘df‘ looks like:
date data 0 2020-01-01 00:00:00 60 1 2020-01-01 01:00:00 94 2 2020-01-01 02:00:00 96 3 2020-01-01 03:00:00 18 4 2020-01-01 04:00:00 90
To change the date-time format, we use the
pd.to_datetime method and pass in the format argument:
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S') df['date'] = df['date'].dt.strftime('%m/%d/%Y %H:%M:%S')
n this example, we are converting the date-time format from
'%Y-%m-%d %H:%M:%S' to
'%m/%d/%Y %H:%M:%S'. The
dt.strftime method is used to format the date-time data as per the desired format.
The resulting dataframe
df will look like this:
date data 0 01/01/2020 00:00:00 60 1 01/01/2020 01:00:00 94 2 01/01/2020 02:00:00 96 3 01/01/2020 03:00:00 18 4 01/01/2020 04:00:00 90
Last but not least, modifying the date-time format in Pandas only requires a small amount of code. The two main methods for formatting date-time data in Pandas are pd.to_datetime and dt.strftime. With these techniques, you can quickly adapt the date-time format to your requirements, streamlining and speeding up the data analysis process.