當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python date replace()用法及代碼示例


Python date.replace() 方法

date.replace() 方法用於操作模塊 datetime 的日期類對象。

它用於用相同的值替換日期,除了那些由括號中指定的關鍵字參數賦予新值的參數。它是一個實例方法,這意味著它適用於類的實例。

模塊:

    import datetime

類:

    from datetime import date

用法:

    replace(year=self.year, month=self.month, day=self.day)

參數:

  • year:實例的新年份值(範圍:1 <= 年份 <= 9999)
  • month:實例的新月份值(範圍:1 <= 月份 <= 12)
  • day:實例的新日期(範圍:1<= 天 <= 31)

如果值不在給定範圍內,則會引發 ValueError。

返回值:

該方法的返回類型是替換參數後的日期類對象。

例:

## Python program explaining the 
## use of date class instance methods

from datetime import date

## Creating an instance
x = date(2019, 9, 25)
print("Current date is:", x)
print()

## Using replace() method 
d = x.replace(year = 2020)
print("New date after changing the year:", d)
print()

d = x.replace(month=1)
print("The date after changing the month:", d)
print()

d = x.replace(day=30)
print("The date after changing the day:", d)
print()

d = x.replace(year=2025, day=30)
print("The date after changing the day and year:", d)
print()

d = x.replace(year= 1999, month =12, day=3)
print("The date after changing the year, month and day:", d)
print()

輸出

Current date is:2019-09-25

New date after changing the year:2020-09-25

The date after changing the month:2019-01-25

The date after changing the day:2019-09-30

The date after changing the day and year:2025-09-30

The date after changing the year, month and day:1999-12-03

注意:

如果任何參數超出範圍或新日期無效,該方法將顯示錯誤。例如,二月有 28(或 29)天,因此如果您為非閏年輸入 29,它將顯示 ValueError。

例:

## Python program explaining the 
## use of date class instance methods

from datetime import date

## Creating an instance
x = date(2019, 9, 25)
print("Current date is:", x)
print()

d = x.replace(year = 2020, month =2, day =29)
print("New date:",d)
print()

d = x.replace(year = 2019, month =2, day =29)
print(d)

輸出

Current date is:2019-09-25

New date:2020-02-29

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    d = x.replace(year = 2019, month =2, day =29)
ValueError:day is out of range for month

運行時錯誤:

ValueError:日期超出月份的範圍



相關用法


注:本文由純淨天空篩選整理自 Python date replace() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。