Python time replace() Method with Example

Python time.replace() Method: In this tutorial, we will learn about the replace() method of time class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python time.replace() Method

The time.replace() method is used 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

The following module is required to use replace() method:

import datetime

Class

The following class is required to use replace() method:

from datetime import time

Syntax

The following is the syntax of replace() method:

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

Parameter(s)

The following are the 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 of time replace() Method in Python

## 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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.