Python DateTime – time.replace() Method with Example
Last Updated :
23 Aug, 2021
In this article, we will discuss the time.replace() method in Python. This 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.
Syntax: replace(year=self.year, month=self.month, day=self.day)
Parameters:
- Year: New year value (range: 1 <= year <= 9999)
- month: New month value(range: 1 <= month <= 12)
- day: New day value(range: 1<= day <= 31)
Returns: New datetime object.
Python program to get time and display:
Python3
from datetime import time
x = time( 5 , 34 , 7 , 6789 )
print ( "Time:" , x)
|
Output:
Time: 05:34:07.006789
Example 1: Python program to replace hour from the given time
Python3
from datetime import time
x = time( 5 , 34 , 7 , 6789 )
print ( "Actual Time:" , x)
final = x.replace(hour = 10 )
print ( "New time after changing the hour:" , final)
|
Output:
Actual Time: 05:34:07.006789
New time after changing the hour: 10:34:07.006789
Example 2: Python program to replace minute from time
Python3
from datetime import time
x = time( 5 , 34 , 7 , 6789 )
print ( "Actual Time:" , x)
final = x.replace(minute = 12 )
print ( "New time after changing the minute:" , final)
|
Output:
Actual Time: 05:34:07.006789
New time after changing the minute: 05:12:07.006789
Example 3: Python code to replace seconds
Python3
from datetime import time
x = time( 5 , 34 , 7 , 6789 )
print ( "Actual Time:" , x)
final = x.replace(second = 2 )
print ( "New time after changing the second:" , final)
|
Output:
Actual Time: 05:34:07.006789
New time after changing the second: 05:34:02.006789
Example 4: Python program to replace all at a time
Python3
from datetime import time
x = time( 5 , 34 , 7 , 6789 )
print ( "Actual Time:" , x)
final = x.replace(hour = 10 , minute = 11 ,
second = 1 , microsecond = 1234 )
print ( "New time :" , final)
|
Output:
Actual Time: 05:34:07.006789
New time : 10:11:01.001234
Share your thoughts in the comments
Please Login to comment...