ADVERTISEMENT
ADVERTISEMENT

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.

Module:

    import datetime

Class:

    from datetime import time

Syntax:

    replace(
        hour=self.hour, 
        minute=self.minute, 
        second=self.second, 
        microsecond=self.microsecond, 
        tzinfo=self.tzinfo, 
        * fold=0
        )

Parameter(s):

  • 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.

Example:

## 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)
print()

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

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

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

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

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

Output

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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

© https://www.includehelp.com some rights reserved.