import pandas as pd
time_stamps = pd.Series(pd.date_range(start='01/01/22', end = '01/02/22', freq='6H'))
print(time_stamps)

This will return the following Pandas Series:

0   2022-01-01 00:00:00
1   2022-01-01 06:00:00
2   2022-01-01 12:00:00
3   2022-01-01 18:00:00
4   2022-01-02 00:00:00
dtype: datetime64[ns]

If we look at one of the series rows, we’ll see it’s a Timestamp object:

time_stamps[0]

Will return:

Timestamp('2022-01-01 00:00:00')

We can obviously convert the Timestamp individually, but we would prefer to instead convert the entire Series to a list of Python Datetimes using a list comprehension:

dt_lst= [element.to_pydatetime() for element in list(time_stamps)]

Convert a DataFrame column of timestamps to dates

#create a DataFrame
times = pd.DataFrame (time_stamps, columns=['time_ts']) 
times['time_dt'] = pd.to_datetime(times['time_ts']).dt.date
times

Here’s our result:

time_ts time_dt
0 2022-01-01 00:00:00 2022-01-01
1 2022-01-01 06:00:00 2022-01-01
2 2022-01-01 12:00:00 2022-01-01
3 2022-01-01 18:00:00 2022-01-01
4 2022-01-02 00:00:00 2022-01-02

Related learning

Categories Python - Data Analysis