In this article, we will see how to change datetime format in Python Pandas.

Python Pandas has the ability to convert a string representation of a date or time into a DateTime object.

Let us assume we have a dataset where the dates and times are represented in different formats. In such a cases pandas are very useful.

Let us create a simple data frame with some date & time data.

import pandas as pd

df = pd.DataFrame({
   'date': ['2021-02-15', '2021-02-16', '2021-02-17'],
   'time': ['12:30:00', '13:45:00', '15:00:00']
})

Here, we are going to use the function called pd.to_datetime() Which takes the string date time in string representation and converts it into DateTime object.

In the above example, The date column is in the format YYYY-MM-DD and the time column is in the format HH:MM:SS.

df['date'] = pd.to_datetime(df['date'])
df['time'] = pd.to_datetime(df['time'], format='%H:%M:%S')

In the previous example, the date column is converted to a DateTime object using the default format of YYYY-MM-DD, and the time column is converted to a DateTime object using the format string ā€˜%H:%M:%Sā€™. This format string specifies the parser to convert the input string to hours, minutes, and seconds.

Using the dt.strftime() method, we can now change the data format. This method accepts a format string and returns the DateTime object as a string.

df['date'] = df['date'].dt.strftime('%d-%m-%Y')
df['time'] = df['time'].dt.strftime('%I:%M %p')

In the above example, dt.strftime() method is used to change the format of the date column to DD-MM-YYYY and the format of the time column to hh:mm AM/PM.

Categorized in:

Tagged in: