PythonDatetime.date类的replace()函数
replace()函数用于操作DateTime 模块的DateTime 类对象。通常,它会替换日期(年、月、日)并返回一个新的 DateTime 对象。
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.
示例 1:用 datetime 对象替换年份。
Python3
# import module
from datetime import date
# Creating an instance
# of datetime
Date = date(2010, 2, 12)
print("Original date : ", Date)
# Using replace() method
New_date = Date.replace(year=2021)
print("After Modify the year:", New_date)
Python3
# import module
from datetime import date
# Creating an instance
# of datetime
Date = date(2010, 2, 12)
print("Original date : ", Date)
# Using replace() method
New_date = Date.replace(month=5)
print("After Modify the month:", New_date)
Python3
# import module
from datetime import date
# Creating an instance
# of datetime
Date = date(2010, 2, 12)
print("Original date : ", Date)
# Using replace() method
New_date = Date.replace(day=21)
print("After Modify the day:", New_date)
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 : 2010-02-12
After Modify the year: 2021-02-12
示例 2:用 datetime 对象替换月份。
蟒蛇3
# import module
from datetime import date
# Creating an instance
# of datetime
Date = date(2010, 2, 12)
print("Original date : ", Date)
# Using replace() method
New_date = Date.replace(month=5)
print("After Modify the month:", New_date)
输出
Original date : 2010-02-12
After Modify the month: 2010-05-12
示例 3:将日期替换为 datetime 对象。
蟒蛇3
# import module
from datetime import date
# Creating an instance
# of datetime
Date = date(2010, 2, 12)
print("Original date : ", Date)
# Using replace() method
New_date = Date.replace(day=21)
print("After Modify the day:", New_date)
输出
Original date : 2010-02-12
After Modify the day: 2010-02-21
示例 4:用 datetime 对象替换时间。
蟒蛇3
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