
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Python Pandas - Converting to timestamp
As we know that Pandas Timestamp represents specific points in time, like Python datetime.datetime. In Pandas, you can convert various objects representing date and time into timestamp using the to_datetime() function, which helps manage and analyze time-series data with ease.
In this tutorial, we will learn about the methods for converting various date formats to Pandas timestamps, converting timestamps back to epoch format, and handling time zones.
Converting Epoch Timestamps to Timestamps
Pandas supports converting integer or float epoch times (i.e., time since January 1, 1970 UTC) into timestamps using the pd.to_datetime(), specifying the unit like "s" for seconds, "ms" for milliseconds, etc.
Example
The following example converts an integer list representing seconds since the epoch into timestamp using the to_datatime() method.
import pandas as pd # Create a list of integer epoch times epoch_seconds = [1439720105, 143806505] # Convert seconds since epoch to Timestamp print('Converted epoch seconds to timestamp:') print(pd.to_datetime(epoch_seconds, unit="s"))
Following is the output of the above code −
Converted epoch seconds to timestamp: DatetimeIndex(['2015-08-16 10:15:05', '1974-07-23 10:15:05'], dtype='datetime64[ns]', freq=None)
Converting Timestamps Back to Epoch
To convert timestamps back to epoch format can be done by subtracting the epoch (i.e., time since January 1, 1970 UTC) and then apply the floor division by the "unit" (1 second). This is helpful for transforming dates back to raw time data for calculations or storage purposes.
Example
The following example converts list of Pandas timestamps back to epoch format.
import pandas as pd # Create timestamp timestamps = pd.date_range("2024-11-04 18:15:05", periods=4, freq="D") # Display the input timestamps print("Input Timestamps:") print(timestamps) # Convert a timestamp to epoch time in seconds epoch_time = (timestamps - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s") print("\nOutput Timestamp to epoch time in seconds:") print(epoch_time)
Following is the output of the above code −
Input Timestamps: DatetimeIndex(['2024-11-04 18:15:05', '2024-11-05 18:15:05', '2024-11-06 18:15:05', '2024-11-07 18:15:05'], dtype='datetime64[ns]', freq='D') Output Timestamp to epoch time in seconds: Index([1730744105, 1730830505, 1730916905, 1731003305], dtype='int64')
Converting Timestamp to Python Datetime
To convert a Pandas Timestamp object to a native Python datetime object can be done by using the to_pydatetime() method.
Example
Following example demonstrates converting the Pandas Timestamp object to a native Python datetime object using the to_pydatetime() method.
import pandas as pd # Create timestamp timestamps = pd.date_range("2024-11-04 18:15:05", periods=4, freq="D") # Display the input timestamps print("Input Timestamps:") print(timestamps) # convert timestamp to native Python datetime object print("\nConverted Python datetime objects:") print(timestamps.to_pydatetime())
Following is the output of the above code −
Input Timestamps: DatetimeIndex(['2024-11-04 18:15:05', '2024-11-05 18:15:05', '2024-11-06 18:15:05', '2024-11-07 18:15:05'], dtype='datetime64[ns]', freq='D') Converted Python datetime objects: [datetime.datetime(2024, 11, 4, 18, 15, 5) datetime.datetime(2024, 11, 5, 18, 15, 5) datetime.datetime(2024, 11, 6, 18, 15, 5) datetime.datetime(2024, 11, 7, 18, 15, 5)]
Converting PeriodIndex to Timestamp
A PeriodIndex object holds ordinal values indicating regular periods in time. Which is nothing but a span of time with a specific frequency. Converting a PeriodIndex object to timestamp can be possible by using the to_timestamp() method.
Example
The following example demonstrates converting the PeriodIndex object to DatetimeIndex (timestamp) using the to_timestamp() method.
import pandas as pd # Create a PeriodIndex object periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45', '2020-07-15 02:55:15', '2022-06-25 09:40:55'], freq="Y") # Display PeriodIndex object print("PeriodIndex...\n", periodIndex) # Display PeriodIndex frequency print("\nPeriodIndex frequency object...\n", periodIndex.freq) # Display PeriodIndex frequency as string print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr) # Convert PeriodIndex to timestamp print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp())
This will produce the following output −
PeriodIndex... PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]') PeriodIndex frequency object... <YearEnd: month=12> PeriodIndex frequency object as a string... A-DEC PeriodIndex object to timestamp... DatetimeIndex(['2021-01-01', '2019-01-01', '2020-01-01', '2022-01-01'], dtype='datetime64[ns]', freq=None)
Convert DataFrame Column to Timestamp
To create Timestamps from multiple DataFrame columns (e.g., year, month, day), you can use pd.to_datetime() method on the selected columns of a DataFrame.
Example
The following example shows the creation of Timestamps from multiple DataFrame columns using the pd.to_datetime() method.
import pandas as pd # Create the DataFrame with multiple columns df = pd.DataFrame({"year": [2024, 2023], "month": [2, 3], "day": [4, 5]}) # display the input DataFrame print("Input DataFrame:") print(df) # Convert multiple DataFrame columns to timestamps print("\nConverted Timestamp:") print(pd.to_datetime(df))
Following is the output of the above code −
Input DataFrame: year month day 0 2024 2 4 1 2023 3 5 Converted Timestamp: 0 2024-02-04 1 2023-03-05 dtype: datetime64[ns]