replace() Function Of Datetime.date Class In Python
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
# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(year=2021)print("After Modify the year:", New_date) |
Original date : 2010-02-12 After Modify the year: 2021-02-12
Example 2: Replace the month with datetime object.
Python3
# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(month=5)print("After Modify the month:", New_date) |
Original date : 2010-02-12 After Modify the month: 2010-05-12
Example 3: Replace the day with datetime object.
Python3
# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(day=21)print("After Modify the day:", New_date) |
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) |
Original date and time : 2010-02-12 08:50:23 After modify date and time : 2010-02-12 01:03:12
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course


