📜  Python的Datetime.replace()函数

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

Python的Datetime.replace()函数

Datetime.replace()函数用于用给定的参数替换 DateTime 对象的内容。

笔记:



  • 在 replace() 中,我们只能传递 DateTime 对象已有的参数,替换 DateTime 对象中不存在的参数将引发错误
  • 它不会替换原来的 DateTime 对象,而是返回一个修改过的 DateTime 对象

示例 1:将当前日期的年份替换为 2000 年。

Python3
# importing the datetime module
import datetime
  
# Getting current date using today()
# function of the datetime class
todays_date = datetime.date.today()
print("Original Date:", todays_date)
  
# Replacing the todays_date year with
# 2000 using replace() function
modified_date = todays_date.replace(year=2000)
print("Modified Date:", modified_date)


Python3
# importing the datetime module
import datetime
  
# Getting current date using today()
# function of the datetime class
todays_date = datetime.date.today()
print("Original Date:", todays_date,)
  
# Trying to replace the todays_date hour
# with 3 using replace() function
modified_date = todays_date.replace(hour=3)
print("Modified Date:", modified_date)


Python3
# importing the datetime module
import datetime
  
# Getting current date and time using now()
# function of the datetime class
todays_date = datetime.datetime.now()
print("Today's date and time:", todays_date)
  
# Replacing todays_date hour with 3 and day
# with 10 using replace() function using hour
# and day parameter
modified_date = todays_date.replace(day = 10, hour=3)
print("Modified date and time:", modified_date)


输出:

Original Date: 2021-07-27
Modified Date: 2000-07-27

示例 2:替换日期时间对象中不存在的参数。

蟒蛇3

# importing the datetime module
import datetime
  
# Getting current date using today()
# function of the datetime class
todays_date = datetime.date.today()
print("Original Date:", todays_date,)
  
# Trying to replace the todays_date hour
# with 3 using replace() function
modified_date = todays_date.replace(hour=3)
print("Modified Date:", modified_date)

输出:

所以我们观察到我们得到一个错误,因为 datetime 对象中不存在小时。现在我们将创建一个带有小时属性的日期时间对象并尝试将其更改为 03,我们还将日期更改为 10。

蟒蛇3

# importing the datetime module
import datetime
  
# Getting current date and time using now()
# function of the datetime class
todays_date = datetime.datetime.now()
print("Today's date and time:", todays_date)
  
# Replacing todays_date hour with 3 and day
# with 10 using replace() function using hour
# and day parameter
modified_date = todays_date.replace(day = 10, hour=3)
print("Modified date and time:", modified_date)

输出:

Today's date and time: 2021-07-28 09:08:47.563144
Modified date and time: 2021-07-10 03:08:47.563144