📜  PythonDatetime.date类的replace()函数

📅  最后修改于: 2022-05-13 01:55:35.243000             🧑  作者: Mango

PythonDatetime.date类的replace()函数

replace()函数用于操作DateTime 模块的DateTime 类对象。通常,它会替换日期(年、月、日)并返回一个新的 DateTime 对象。

示例 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