replace() method of time class in Python

The replace() method of the time class replaces one or more attributes of a time object as specified by its parameters.Example for replace() are given.

Time Updated 16 Feb 2017 1 min read

Method Name

replace

Method Signature

replace(hour=self.hour, minute=self.minute,

second=self.second, microsecond=self.microsecond,

tzinfo=self.tzinfo, * fold=0)

Method Overview

The replace() method of a time instance, replaces only the attributes corresponding to the one or more specified parameters and returns a time instance.

Return Type

datetime.time

Example1 – Replace hours of a time object

python
import datetime

# Create a date object with today's date

d1 = datetime.datetime.today()

print("Today's date: {}".format(d1))

# Create a time object out of a date object

t1 = d1.time()

print("Only the time: {}".format(t1))

# Replace the time of t1 - set hours to 15

t2 = t1.replace(hour=15)

print("New time: {} ".format(t2))

Output

Output
Today's date: 2017-02-16 20:47:24.807864

Only the time: 20:47:24.807864

New time: 15:47:24.807864

Example1 – Replace attributes of a time object with values of a tuple

python
import datetime

# create a time object with time attributes set as zero

t1 = datetime.time()

print(t1)

# Create a tuple required for instantiating a time object

timeTuple       = (21,30,45,99999)

# Replace the 't1' time instance, with attributes coming from the tuple – using splat operator

timeFromTuple   = t1.replace(*timeTuple)

print(timeFromTuple)

Output

Output
00:00:00

21:30:45.099999