
- 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 - Timestamp
The Timestamp object in the Python Pandas library, is an essential scalar type for handling date and time data. The Timestamp is a subclass of datetime.datetime, designed to offer a more flexible alternative for datetime operations within Pandas. A timestamped data represents the most basic type of time series data that associates values with points in time.
In this tutorial you will learn about creating and working with Pandas Timestamp objects.
The Timestamp Class
The Timestamp class is a specialized datetime object designed to handle timezone-aware and timezone-naive datetime data in pandas. As a subclass of Python's datetime.datetime, Timestamp objects offer enhanced functionality for indexing, manipulating, and converting time data. Missing datetime values are represented as NaT (Not a Time).
Syntax
Following is the syntax of the Timestamp() class −
class pandas.Timestamp(ts_input=<object>, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, nanosecond=None, tz=None, unit=None, fold=None)
Where,
ts_input: A datetime-like object, string, integer, or float to convert to a Timestamp.
year, month, day: Specify the year, month, and day for the timestamp.
hour, minute, second, microsecond: Optional time values, by default these are set to 0.
tzinfo: Optional datetime.tzinfo information. By default None.
tz: An optional string representing a timezone information, such as pytz or dateutil timezone.
unit: Specifies the unit of input for int/float types (e.g., s for seconds, ms for milliseconds).
fold: Handles ambiguous times during daylight saving transitions.
Creating a Timestamp Object
The pandas.Timestamp() constructor can be used to create Timestamp from a variety of inputs, including datetime objects, strings, and integer inputs.
Example: Creating Timestamp from a datetime object
The following example creates the Pandas Timestamp object using a datetime object.
import pandas as pd import datetime # Creating Timestamp from a datetime object ts = pd.Timestamp(datetime.datetime(2024, 11, 1)) print('Created Timestamp:', ts) print(type(ts))
Following is the output of the above code −
Created Timestamp: 2024-11-01 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Example: Creating Timestamp from a String
The following example creates the Pandas Timestamp object using a Python string representing a date.
import pandas as pd import datetime # Creating Timestamp from a date string ts = pd.Timestamp("2024-11-01") print('Created Timestamp:', ts) print(type(ts))
Following is the output of the above code −
Created Timestamp: 2024-11-01 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Example: Creating Timestamp with the Integer Values
The following example creates the Pandas Timestamp object using the integer values.
import pandas as pd import datetime # Creating Timestamp directly with year, month, day arguments ts = pd.Timestamp(2024, 11, 1) print('Created Timestamp:', ts) print(type(ts))
Following is the output of the above code −
Created Timestamp: 2024-11-01 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Creating Timestamp using the to_datetime()
The to_datetime() function creates timestamp from various formats like strings, lists of dates, or integers.
Example
The following example creates a Timestamp from a list of strings using the pd.to_datetime() function.
import pandas as pd import datetime # Converting a list of date strings to Timestamp date_string = pd.to_datetime(["2024-07-31", "2024-10-1", None]) print("Timestamp from list of date strings:", date_string)
Following is the output of the above code −
Timestamp from list of date strings: DatetimeIndex(['2024-07-31', '2024-10-01', 'NaT'], dtype='datetime64[ns]', freq=None)
Creating Timestamp Ranges
To create ranges of Timestamp, you can use the pd.date_range() function.
Example
The following example creates a range of Timestamps using the pd.date_range() function.
import pandas as pd import datetime # Generating a range of timestamps index = pd.date_range(start='2024-01-01', end='2024-01-10') print(index)
Following is the output of the above code −
DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10'], dtype='datetime64[ns]', freq='D')
Timestamps with Series and DataFrames
Pandas Timestamp can be used as indices in Series and DataFrames, automatically converting lists of Timestamp into DatetimeIndex.
Example
The following example creates a pandas Series object with a DatetimeIndex using the the list of Timestamps.
import pandas as pd import numpy as np # Creating a Series with Timestamps as index dates = [pd.Timestamp("2024-05-01"), pd.Timestamp("2024-05-02"), pd.Timestamp("2024-05-03")] ts = pd.Series(np.random.randn(3), index=dates) # Accessing the index type print("Checking the type of the index:", type(ts.index)) print("Output Timestamped Series:", ts)
On executing the above code you will get the following results −
Checking the type of the index: <class 'pandas.core.indexes.datetimes.DatetimeIndex'> Output Timestamped Series: 2024-05-01 -0.344069 2024-05-02 0.717256 2024-05-03 0.946290 dtype: float64
Timestamps vs. Time Spans
Timestamps represent points in time, they can serve as indices in pandas objects and are converted to DatetimeIndex for list inputs. Whereas time spans time spans ranges (known as regular intervals of time).
Example
The following example demonstrates the difference between Timestamp and Time Span objects in Pandas.
import pandas as pd # Create Timestamps start = pd.Timestamp('2024-01-01') end = pd.Timestamp('2024-01-10') # Create Time span from Timestamps span = pd.date_range(start, end) print("Timestamp:", start) print("\nTime Span:", span)
Following is the output of the above code −
Timestamp: 2024-01-01 00:00:00 Time Span: DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10'], dtype='datetime64[ns]', freq='D')
Working with Epoch Timestamps
Epoch timestamps (i.e., time since January 1, 1970 UTC), which represent time in seconds or milliseconds. Use the unit parameter to specify the time unit (e.g., s for seconds, ms for milliseconds).
Example
The following example creates a timestamp from an Epoch.
import pandas as pd # Float input with unit 's' (seconds) ts = pd.Timestamp(1719469200.5, unit='s') print("Created Timestamp using Epoch:", ts)
Following is the output of the above code −
Created Timestamp using Epoch: 2024-06-27 06:20:00.500000
Timestamp Limitations
The limits of timestamp representation depend on the chosen resolution. At nanosecond resolution, the representable time span is approximately 584 years.
Example
The following example represents the timestamp minimum and maximum limits.
import pandas as pd print("Timestamp min:", pd.Timestamp.min) print("Timestamp max:", pd.Timestamp.max)
Following is the output of the above code −
Timestamp min: 1677-09-21 00:12:43.145224193 Timestamp max: 2262-04-11 23:47:16.854775807