Python time replace() Method with Example

Python time.replace() Method: Here, we are going to learn about the replace() method of time class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 04, 2020

Python time.replace() Method

time.replace() method is used to manipulate objects of time class of module datetime.

It is used to replace the time with the same value, except for those parameters given new values by whichever keyword arguments are specified in the brackets. It is an instance method which means that it works on an instance of the class.


    import datetime


    from datetime import time


        * fold=0


  • hour: in range(24)
  • minute: in range(60)
  • second: in range(60)
  • microsecond: in range(1000000)
  • tzinfo: object passed as the tzinfo argument to the datetime constructor, or None if none was passed
  • fold: [0,1]

If values are not in the given range a ValueError is raised.

Return value:

The return type of this method is a time class object after replacing the parameters.


## Python program explaining the 
## use of replace() method

from datetime import time

## Creating an instance
x = time(4,54,23, 37777)
print("Time entered was:", x)

## Using replace() method 
d = x.replace(hour = 22)
print("New time after changing the hour:", d)

d = x.replace(minute=10)
print("New time after changing the minute:", d)

d = x.replace(second=30)
print("Time after changing the second:", d)

d = x.replace(hour=20, minute=30)
print("Time after changing hour and minute:", d)

d = x.replace(hour= 19, minute =12, second=34, microsecond=3333)
print("Time after changes:", d)


Time entered was: 04:54:23.037777

New time after changing the hour: 22:54:23.037777

New time after changing the minute: 04:10:23.037777

Time after changing the second: 04:54:30.037777

Time after changing hour and minute: 20:30:23.037777

Time after changes: 19:12:34.003333

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.