241
You can use the following basic syntax to convert a timestamp to a datetime in a pandas DataFrame:
timestamp.to_pydatetime()
The following examples show how to use this function in practice.
Example 1: Convert a Single Timestamp to a Datetime
The following code shows how to convert a single timestamp to a datetime:
#define timestamp stamp = pd.Timestamp('2021-01-01 00:00:00') #convert timestamp to datetime stamp.to_pydatetime() datetime.datetime(2021, 1, 1, 0, 0)
Example 2: Convert an Array of Timestamps to Datetimes
The following code shows how to convert an array of timestamps to a datetime:
#define array of timestamps stamps = pd.date_range(start='2020-01-01 12:00:00', periods=6, freq='H') #view array of timestamps stamps DatetimeIndex(['2020-01-01 12:00:00', '2020-01-01 13:00:00', '2020-01-01 14:00:00', '2020-01-01 15:00:00', '2020-01-01 16:00:00', '2020-01-01 17:00:00'], dtype='datetime64[ns]', freq='H') #convert timestamps to datetimes stamps.to_pydatetime() array([datetime.datetime(2020, 1, 1, 12, 0), datetime.datetime(2020, 1, 1, 13, 0), datetime.datetime(2020, 1, 1, 14, 0), datetime.datetime(2020, 1, 1, 15, 0), datetime.datetime(2020, 1, 1, 16, 0), datetime.datetime(2020, 1, 1, 17, 0)], dtype=object)
Example 3: Convert a Pandas Column of Timestamps to Datetimes
The following code shows how to convert a pandas column of timestamps to datetimes:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'stamps': pd.date_range(start='2020-01-01 12:00:00',
periods=6,
freq='H'),
'sales': [11, 14, 25, 31, 34, 35]})
#convert column of timestamps to datetimes
df.stamps = df.stamps.apply(lambda x: x.date())
#view DataFrame
df
stamps sales
0 2020-01-01 11
1 2020-01-01 14
2 2020-01-01 25
3 2020-01-01 31
4 2020-01-01 34
5 2020-01-01 35
Additional Resources
How to Convert Datetime to Date in Pandas
How to Convert Columns to DateTime in Pandas
How to Sort a Pandas DataFrame by Date