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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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.

Open Compiler
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
Advertisements