Pandas Datetime to String

Pandas is a Python toolkit for data analysis and manipulation that is simple, flexible, powerful, fast, and open-source. It is instrumental when dealing with large datasets for cleaning, analyzing, altering, and examining data.

The Python library for pandas allows programmers to examine enormous amounts of data and interpret or make statistical conclusions. It can quickly clean a large dataset to make it understandable, readable, and analyzeable. You can use it to create a relationship or detect a correlation between data. You can use it to conduct any mathematical operation on the data, such as sum, average, max, min, etc.

Pandas also have a data cleaning feature that allows you to eliminate undesirable or unnecessary data, NULL or empty data, and incorrect data from a dataset. You can use the pip pandas command to install it quickly. However, some Python distributions, such as Spyder and Anaconda, come with the pandas library preinstalled. As a result, if you’re using these distributors to write your code, you have to import the panda’s library into your program, and you’re ready to go.

You can now utilize the pandas’ library’s modules and functions in your program after you’ve imported the library. This tutorial will show you how to convert a DateTime to a string in Python using the Pandas package. We’ll show you how to convert DateTime to string in Python utilizing the panda’s module with some basic and easy-to-understand examples. So let’s get started.

Pandas Datetime to String

Using a date, time, or datetime object, the strftime() method returns a string representing the date and time.

Example 1: converting a datetime to a string with strftime()

The following application transforms a datetime object with the current date and time to several string formats.

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)	

What is the working of strftime()?

The format codes in the software, as mentioned above, are %Y, % m, % d, and so on. The strftime() method accepts one or more format codes as input and produces a formatted string. The datetime class is imported from the datetime module. The strftime() method can be accessed by objects of the datetime type.

from datetime import datetime

The now variable has the datetime object holding the current date and time saved.

now = datetime.now()

To create formatted strings, use the strftime() function.

year = now.strftime("%Y")

The strftime() method accepts a string that may have several format codes.

date_time =now.strftime("%m/%d/%Y, %H:%M:%S")

Example 2: Using a timestamp to create a string

from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

print("Date time object:", date_time)
d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("Output 2:", d)

d = date_time.strftime("%d %b, %Y")
print("Output 3:", d)

d = date_time.strftime("%d %B, %Y")
print("Output 4:", d)

d = date_time.strftime("%I%p")
print("Output 5:", d)

Example 3: The appropriate date and time for the locale

from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

d = date_time.strftime("%c")
print("Output 1:", d)

d = date_time.strftime("%x")
print("Output 2:", d)

d = date_time.strftime("%X")
print("Output 3:", d)

The locale’s suitable date and time representation are represented using % c, % x, and % X format codes.

List of Format Codes

All of the codes passed to the strftime() method are listed below.

DirectiveMeaning
Example
%aThe weekday’s name abbreviation isTue, Wen, …
%AA complete name of the weekday.Thursday, Friday, …
%wa decimal number representing a weekday0, 1, 2 …, 6
%dMonths’ Day as a zero-padded decimal.01, 02,03,04 …, 31
%-dMonth’s Day as a decimal number.1, 2, …, 30
%bAbbreviated month name.Jan, Feb, …, Dec
%BFull month name.January, February, …
%mMonth as a zero-padded decimal number.01, 02, …, 12
%-mMonth as a decimal number.1, 2,3 …, 12
%yThe year with no century as a decimal number with no zero-padding.00, 01, …, 99
%-yThe year with no century as a decimal number.0, 1, …, 99
%YThe year with century representation as a decimal number.2015, 2022, etc.
%HHour (24-hour clock) as a decimal number with zero-padding.00, 01,02 …, 23
%-HHour (24-hour clock) representation as a decimal number.0, 1,2,3 …, 23
%IHour (12-hour clock) representation as a decimal number with zero-padding.01, 02, 03, …, 12
%-IHour (12-hour clock) decimal number representation.1, 2, 3,4 … 12
%pLocale’s AM or PM.AM, PM
%MMinute as a decimal number with zero-padding.00, 01,02,03, …, 59
%-MMinute decimal number representation.0, 1, 2, 3 …, 59
%SSecond, as a zero-padded decimal number.00, 01, 02, 03, …, 59
%-SSecond as a decimal number.0, 1, 2, 3 …, 59
%fMicrosecond’s decimal number representation, with left zero-padding.000000 – 999999
%zThe form +HHMM or -HHMM UTC offset.
%Zrepresents the name of the Time zone.
%j
year’s day as a decimal number with zero-padding.001, 002, 003, …, 366
%-jyear’s days as a decimal number.1, 2,3,4, …, 366
%UYear’s week number (Sunday – weeks’ first day). All days in a new year before the first Sunday are considered in week 0.00, 01, 02, 03, …, 53
%WYear’s week number (Week’s first day as Monday ). All days in a new year before the first Monday are considered in week 0.00, 01, …, 53
%cLocale’s appropriate date and time representation.Mon Sep 30 07:06:05 2013
%xLocale’s appropriate date representation.09/30/13
%XLocale’s appropriate time representation.07:06:05
%%A literal ‘%’ character.%



Example: Convert DateTime to String in Pandas

Let’s say we have the pandas DataFrame below, which shows the sales of a store on four special days:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'day': pd.to_datetime(pd.Series(['20220102', '20220104',
                                                    '20220108', '20220109'])),  'sales': [1540, 1945, 2584, 2390]})

#view DataFrame
df

The dtypes function is used to see the data type of each column in the DataFrame:

#view data type of each column
df.dtypes

The "day" column has a DateTime class, as can be seen.  We can use the following syntax to transform "day" to a string:

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

#view updated DataFrame
df

To confirm that the "day" column is now a string, we may use the dtypes function once more:


#view data type of each column
df.dtypes

Example: Convert the DateTime to string

To convert the DateTime to string in this example, we’ll utilize the lambda and DataFrame.style.format() functions. Take a look at the following example command:

import pandas as pd

PresentationTimeTable = ({

   'Presentations':["Health","Sleep","Writing","Technology"],

   'Time' :["00:32:52","14:15:53","21:42:43","11:20:46"],

   'Date':["2022/03/05","2022/03/09","2022/03/10","2022/03/07"]

})

df = pd.DataFrame(PresentationTimeTable)

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

When you run the command listed above, you will see the following output:

Convert the DateTime to string
Convert the DateTime to string

The result of the DataFrame.style.format() function is identical to that of the pandas.Series.dt.strftime() function, as you can see. As a result, using pandas in Python to convert a datetime to a string is simple.

Example: Convert DateTime to String

To convert DateTime to string, we use pandas.Series.dt.strftime() function in the next example. Here’s an example of code:

import pandas as pd

PresentationTimeTable = ({

   'Presentations':["Health","Sleep","Writing","Technology"],

   'Time' :["00:32:52","14:15:53","21:42:23","11:20:26"],

   'Date':["2022/03/05","2022/03/09","2022/03/10","2022/03/07"]

})

df = pd.DataFrame(PresentationTimeTable)
df['DateTypeCol'] = pd.to_datetime(df.Date)
df['Converted_Dates'] = df['DateTypeCol'].dt.strftime('%m/%d/%y')
df

The following is the result of the code mentioned above:

Convert DateTime to String
Convert DateTime to String

If you look closely, you’ll notice that the data’s format or order has been altered, indicating that you can now enter the date in your preferred format.

Example: Using pd.to_datetime()

The pd.to_datetime() function is used in this example.

import pandas as pd

PresentationTimeTable = ({

   'Presentations':["Health","Sleep","Writing","Technology"],

   'Time' :["00:32:52","14:15:53","21:42:43","11:20:46"],

   'Date':["2022/03/05","2022/03/09","2022/03/10","2022/03/07"]

})

df = pd.DataFrame(PresentationTimeTable)


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

You’ll get the following output if you run this command:

using pd.to_datetime()
using pd.to_datetime()

Example: Convert a Pandas Series of datetime Objects to their String Equivalents

A Pandas Series refers to a one-dimensional array that can hold any data and labels. Let’s say you’ve got a pandas collection of datetime objects. Using the strftime() function and specific format codes, we can convert a datetime object to its string counterpart. However, converting the datetime objects of a pandas series requires a somewhat different approach. This section will discuss how such a conversion can be accomplished using examples.

Take a look at the code below. It starts by creating a pandas Series of datetime objects, transforming it into a pandas Series of string objects.

import pandas as pd

dates = pd.to_datetime(pd.Series([
    "01/03/2022",
    "02/03/2022",
    "03/03/2022",
    "04/03/2022",
    "05/03/2022"
]), format = '%d/%m/%Y')

print("Before conversion")
print(dates)
print("After conversion")
dates = dates.dt.strftime('%Y-%m-%d')
print(dates)

Take note of the output’s dtype value. The first indicates that the series comprises datetime objects, whereas the second suggests that it contains string objects.

The lambda function is also used to change the data type of objects. For more information, see the code below. The lambda function performs the conversion using the strftime() function.

import pandas as pd

dates = pd.to_datetime(pd.Series([
    "01/03/2022",
    "02/03/2022",
    "03/03/2022",
    "04/03/2022",
    "05/03/2022"
]), format = '%d/%m/%Y')
print("Before conversion")
print(dates)
print("After conversion")
dates = dates.apply(lambda x: x.strftime('%Y-%m-%d'))
print(dates)

Conclusion

In this article, we’ve seen three pandas routines in python used to convert DateTime to string: DataFrame.style.format(), pandas.Series.dt.strftime(), and pd.to_datetime(). We’ve supplied sample examples for each function to help you learn how to utilize them in your projects.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *