How to convert a timestamp to string in pandas?

Our task for today is to cast a datetime /timestamp pandas column to strings objects.

Create example data

Let’s start by importing the pandas module and creating our data. Feel free to use the snippet below to follow along with the example:

import pandas as pd

stamps = pd.Series(pd.date_range(start='1/1/24', periods=6, freq='6h'))
interviews = pd.Series ([24, 33, 26, 32, 27, 17] )

#Initialize the DataFrame

data = pd.DataFrame ((dict(stamps=stamps, interviews = interviews)))


Let’s look into our data:

02024-01-01 00:00:0024
12024-01-01 06:00:0033
22024-01-01 12:00:0026
32024-01-01 18:00:0032
42024-01-02 00:00:0027
52024-01-02 06:00:0017

Look into the stamps column – the data type is datatime64, but if we use the bracket notation we see that the elements are shown as timestamps.


Will return:

Timestamp('2024-01-07 00:00:00')

Note: We can create a single pandas timestamp object also using the pd.Timestamp() method:

stamp_ts = pd.Timestamp ('2024-01-02')

Convert the datetime timestamps to objects in pandas

We use the datetime64 dt accessor and the very flexible strftime formatter to convert your datetime stamps to a string.

data['stamps_str']  = data['stamps'].dt.strftime('%d/%m/%y')

This convert the stamps datetime column to a string with format dd/mm/yyyy – note that after formatting with strftime, the Series / column dtype is object.

02024-01-01 00:00:002401/01/24
12024-01-01 06:00:003301/01/24
22024-01-01 12:00:002601/01/24
32024-01-01 18:00:003201/01/24
42024-01-02 00:00:002702/01/24

In a similar fashion you can convert to other formats such as yyyy-mm-dd (using strftime(‘%y-%m-%d).

If we look into the DataFrame pandas data types we’ll see that the new column has an object data type (representing a string in this case) type.

stamps        datetime64[ns]
interviews             int64
stamps_str            object
dtype: object

We can verify the Python type by looking at the first cell in the stamps_str column:


This will return str – as the object is a Python string.

Cast a pandas timestamp to Python datetime

As we learnt before, if you have a single timestamp variable, you can easily convert it to a datetime using the following Python code:

stamp_ts = pd.Timestamp ('2024-01-02')
my_datetime = stamp_ts.to_pydatetime()

Next learning

How to sum and add up two or more pandas DataFrame columns?