Table of Contents
Converting a timestamp to a datetime in Pandas allows for the manipulation and analysis of time-based data. This process involves utilizing the built-in functions and methods in Pandas to convert the timestamp, which is a single point in time, into a datetime object, which includes both date and time information. This transformation can be achieved by using the to_datetime() function or the astype() method, both of which allow for the customization and formatting of the final datetime output. Overall, converting a timestamp to a datetime in Pandas is a crucial step in effectively working with time-series data in a data analysis project.
Convert Timestamp to Datetime in Pandas
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