Today we’ll learn how to convert timestamps to Python datetime objects. In Pandas we use those terms almost interchangeably though, which renders this a bit confusing.
Creating Pandas timestamps
We can easily create timestamps using the Pandas pd.TimeStamp function. Here is a very simple example to get us started with the tutorial:
import pandas as pd
my_ts = pd.Timestamp('01/01/23')
my_ts
This will return the following time stamp.
Timestamp('2023-01-01 00:00:00')
Cast single timestamp to date
Next, we would like to generate a Python datetime object from our time stamp.
my_dt = ts.to_pydatetime()
This returns a datetime object:
datetime.datetime(2023, 1, 1, 0, 0)
We can manipulate the datetime object as needed to extract the year, date,month and modify the date format as needed
Convert timestamp Series to a list of Python datetimes
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 |