To convert timestamps to datetime objects in Python using Pandas, you can utilize the
pd.to_datetime() function. This function allows you to convert various date and time representations, including timestamps, to Pandas datetime objects.
Here’s an example of converting timestamps to datetime objects using Pandas:
import pandas as pd timestamps = [1622207400, 1622293800, 1622380200] # Example timestamps in Unix format datetime_objects = pd.to_datetime(timestamps, unit='s') print(datetime_objects)
In this example, we import the Pandas library using the
import pandas as pd statement. Then, we define an example list of timestamps named
timestamps. These timestamps are represented as integers in Unix format (seconds since January 1, 1970).
Next, we use the
pd.to_datetime() function and pass the
timestamps list as the first argument. We also specify the
unit parameter as
's' to indicate that the timestamps are in seconds.
The function converts each timestamp to a Pandas datetime object and returns a series of datetime objects, which we assign to the variable
Finally, we print the
datetime_objects, which will display the converted datetime objects:
0 2021-05-28 00:30:00 1 2021-05-29 00:30:00 2 2021-05-30 00:30:00 dtype: datetime64[ns]
Note that the resulting datetime objects have a data type of
datetime64[ns]. You can then use these datetime objects for various operations and analyses in Pandas, such as filtering, grouping, or time series analysis.