replace() Function Of Datetime.date Class In Python
Last Updated :
23 Aug, 2021
replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object.
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.
Example 1: Replace the year with datetime object.
Python3
from datetime import date
Date = date( 2010 , 2 , 12 )
print ( "Original date : " , Date)
New_date = Date.replace(year = 2021 )
print ( "After Modify the year:" , New_date)
|
Output
Original date : 2010-02-12
After Modify the year: 2021-02-12
Example 2: Replace the month with datetime object.
Python3
from datetime import date
Date = date( 2010 , 2 , 12 )
print ( "Original date : " , Date)
New_date = Date.replace(month = 5 )
print ( "After Modify the month:" , New_date)
|
Output
Original date : 2010-02-12
After Modify the month: 2010-05-12
Example 3: Replace the day with datetime object.
Python3
from datetime import date
Date = date( 2010 , 2 , 12 )
print ( "Original date : " , Date)
New_date = Date.replace(day = 21 )
print ( "After Modify the day:" , New_date)
|
Output
Original date : 2010-02-12
After Modify the day: 2010-02-21
Example 4: Replace the time with datetime object.
Python3
from datetime import datetime
Date = datetime( 2010 , 2 , 12 , 8 , 50 , 23 )
print ( "Original date and time : " , Date)
New_date = Date.replace(hour = 1 ,
minute = 3 ,
second = 12 )
print ( "After modify date and time : " , New_date)
|
Output
Original date and time : 2010-02-12 08:50:23
After modify date and time : 2010-02-12 01:03:12
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...