1

摘自 的描述dateutil.relativedelta.relativedelta

年、月、日、时、分、秒、微秒:

Absolute information (argument is singular); adding or subtracting a
relativedelta with absolute information does not perform an aritmetic
operation, but rather REPLACES the corresponding value in the
original datetime with the value(s) in relativedelta.

年、月、周、日、小时、分钟、秒、微秒:

Relative information, may be negative (argument is plural); adding
or subtracting a relativedelta with relative information performs
the corresponding aritmetic operation on the original datetime value
with the information in the relativedelta.

当涉及到加法和减法时,我可以看到与以下示例的差异。

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.now()
>>> str(now)
'2016-05-23 22:32:48.427269'
>>> singular = relativedelta(month=3)
>>> plural = relativedelta(months=3)

# subtracting 
>>> str(now - singular)             # replace the corresponding value in the original datetime with the value(s) in relativedelta
'2016-03-23 22:32:48.427269'
>>> str(now - plural)               # perform the corresponding aritmetic operation on the original datetime value with the information in the relativedelta.
'2016-02-23 22:32:48.427269'

# adding
>>> str(now + singular)             # replace the corresponding value in the original datetime with the value(s) in relativedelta
'2016-03-23 22:32:48.427269'
>>> str(now + plural)               # perform the corresponding aritmetic operation on the original datetime value with the information in the relativedelta.
'2016-08-23 22:32:48.427269'

除此之外,单数和复数参数之间还有什么其他区别relativedelta

4

1 回答 1

1

单数参数是绝对信息,基本上你可以认为relativedelta(month=3)是“三月,相对于它所应用的任何日期和时间”(即替换month关键字)。这不适用于乘法和除法等运算,因此这些运算对绝对信息没有影响:

>>> relativedelta.relativedelta(month=3) * 3
relativedelta(month=3)

复数参数是相对偏移量,所以他们说,“在日期之后/之前给我这几个月”。由于这些是偏移量,因此它们可以进行乘法和除法:

>>> relativedelta.relativedelta(months=3) * 3
relativedelta(months=9)

使用它的一个很好的例子是在tzrange类中,它用于relativedelta模拟 POSIX 样式 TZ 字符串的行为。您可以看到这个 test,它使用以下对象:

tz.tzrange('EST', -18000, 'EDT', -14400,
       start=relativedelta(hours=+2, month=4, day=1, weekday=SU(+1)),
       end=relativedelta(hours=+1, month=10, day=31, weekday=SU(-1)))

这构造了一个等效于 的时区'EST5EDT',其中将startrelativedelta 添加到给定年份的任何日期以查找该年 DST 的开始,并将end其添加到给定年份的任何日期以查找该年 DST 的结束。

分解它:

  • month给你一个四月的约会
  • day在月初开始你
  • weekday=SU(+1)为您提供指定日期或之后的第一个星期日(这是在monthandday参数之后应用的,因此当day设置为 1 时,您将获得该月的第一个星期日)。
  • hours=+2- 这将在应用所有其他内容后给您 2 小时。不过,在这种情况下,可能hour=2对演示这个概念更有意义,因为这些relativedeltas 实际使用的地方我认为首先会去掉时间部分(在午夜给出日期),所以这实际上是在尝试对 2AM 进行编码。
于 2016-05-23T20:42:05.213 回答