How to replace date and time fields of a Timestamp in pandas

Overview

In pandas, pandas.Timestamp contains the replace() function to replace the date and time fields of the given Timestamp object. It is equivalent to Python's datetime object.

Syntax

The replace() function takes the syntax given below:

Timestamp.replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, nanosecond=None, tzinfo=<class 'object'>)
Syntax for the replace() function

Parameters

The replace() function take the following optional parameter values:

  • year, month, and day: This represents the date fields.
  • hour, minute, second, microsecond, and nanosecond: This represents the time fields.
  • tzinfo: This enquires information about the Timestamp object.

Note: The replace() function must take at least one of the date or time fields parameters.

Return value

The replace() function returns a Timestamp object with replaced fields.

Code example

Let's look at the code below:

# A code to illustrate the replace() function in Pandas
# importing the pandas library
import pandas as pd
# creating a Timestamp object
a = pd.Timestamp(1999, 12, 15)
# printing the Timestamp object
print(a)
# replacing the year, month, day and hour
b = a.replace(year=2022, month=4, day=30, hour=9)
print(b)

Code explanation

  • Line 3: We import the pandas library.
  • Line 6: We create a Timestamp object, a.
  • Line 9: We print the value of a.
  • Line 12: We replace the date and time fields of a using the replace() function. The result is assigned to b variable.
  • Line 14: We print the value of b to the console.

Free Resources