当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。