Python

Pandas Datetime to String

Pandas is easy to use, simple, flexible, powerful, fast, and open-source python library used to analyze and manipulate data. It is really very helpful in dealing with datasets for cleaning, analyzing, manipulating, ad exploring the data. The pandas’ python library allows the programmer to analyze a large amount of data and interpret or draw a statistical conclusion. It can quickly clean a huge dataset to make it easy to understand, read, and analyze. It can help you make a relationship or find a correlation between data, or you can perform any mathematical operation like sum, average, max, min, etc., on the data.

Pandas also allows you to remove unwanted or irrelevant, NULL or empty, and wrong data from the dataset called data cleaning. It can be straightforwardly installed using the pip install pandas command. However, some python distributors like Spyder and Anaconda have preinstalled pandas library. Hence, if you are writing your code in these distributors, you have just to import the pandas’ library into your program, and you are good to go.

Once you have imported the pandas’ library, you are ready to use its modules and functions in your program. This tutorial is designed to explain how to convert the DateTime to string using the panda’s library in python. Here, we will provide some simple and easy-to-understand examples to make you learn how to convert DateTime to string using the pandas’ library in python. So let us begin.

In python, the default format of DateTime is YYYY – MM – DD, which is represented as (%Y-%M – %D). Different built-in pandas modules are available, which can convert a DateTime into a string. pandas.Seris.dt.strftime() is the most common method used to convert the DateTime into string. In this article, we will explain how to use the strftime() function to convert the DateTime into a string and also two other functions to_datetime() and DataFrame.style.format() functions to convert the DateTime into a string with the help of examples. Below are the steps you need to follow to convert the DateTime into a string:

Step 1: Collect the data of dates for conversion

The first step is to collect the data of dates that you want to convert into a string. Get the dataset of the DateTime that you want to convert to string, for example, and you may have the following dataset with four different dates; 2022/01/05, 2022/01/09, 2021/05/09, 2020/08/07, time; 00:12:32, 13:45:53, 21:22:23, 11:00:26, courses; Math, Stats, Computer, Chemistry. The dataset represents the timetable of the four courses offered with their subsequent dates and time.

Step 2: Create the data frame of the collected data

Now that you have collected the data for conversion, create the data frame to begin the conversion process. The dataframe will consist of the rows which contain the dataset against each entry and columns containing the provided data, which are dates {2022/01/05, 2022/01/09, 2021/05/09, 2020/08/07}, time {00:12:32, 13:45:53, 21:22:23, 11:00:26}, and course names {Math, Stats, Computer, Chemistry}. See the code below to create the data frame of your timetable data.

import pandas as pd

TimeTable = ({

   'Courses':["Maths","Stats","Computer","Chemistry"],

   'Time' :["00:12:32","13:45:53","21:22:23","11:00:26"],

   'Date':["2022/01/05","2022/01/09","2021/05/09","2020/08/07"]

})

df = pd.DataFrame(TimeTable)

print(df)

Text Description automatically generated

As you can see, the import pandas as pd command are used to import the pandas’ library into the program. And pd.DataFrame() is used to create the DataFrame of the given dataset. When you run the code given above, you will get the following output:

Text, chat or text message Description automatically generated

Step 3: Convert the DateTime to string

Now, the time is to convert the DateTime into a string. In the first instance, we are using pandas.to_datetime() function. See the code below:

Example 1:

This example is about the pd.to_datetime() function.

df['DateTypeCol'] = pd.to_datetime(df.Date)

Text Description automatically generated

When you run this command, you will get the following output:

Text Description automatically generated

Example 2:

In the next example, we are using pandas.Series.dt.strftime() function to convert DateTime to string. Here is the example code:

df['Converted_Dates'] = df['DateTypeCol'].dt.strftime('%m/%d/%y')

Here is the output of the above code:

A black screen with white text Description automatically generated with low confidence

If you observe, you can see that the format or order of the data is also changed, which means you can place the date in your own format as well.

Example 3:

In the third example, we are going to use lambda and DataFrame.style.format() functions to convert the DateTime to string. See the sample command below:

df.style.format({"Date"lambda t: t.strftime("%m/%d/%Y")})

When you run the above-given command, you will get to see the following output:

A black background with white text Description automatically generated with low confidence

As you can see, the output for the DataFrame.style.format() function is the same as for the pandas.Series.dt.strftime() function. Hence, it is simple to convert the datetime into the string using pandas in python.

Conclusion:

In this article, we have seen three pandas functions in python used to convert DateTime to string; DataFrame.style.format() function, pandas.Series.dt.strftime() function, and pd.to_datetime() function. To help you learn how to use these functions, we have provided sample examples for each function so that you can practice them and quickly learn how to use them in your programs.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content