'dateutil.relativedelta.relativedelta'中的单数和复数参数有什么区别?



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中的单数论证和复数论证还有什么区别?

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

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

复数论点是相对的偏移,所以他们说,"在日期之后/之前给我这么多月"。由于这些是一种偏移,它们可以进行乘法和除法运算:

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

tzrange类就是一个很好的例子,它使用relativedelta来模拟POSIX风格TZ字符串的行为。你可以看到这个测试,它使用以下对象:

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'的时区,其中start相对德尔塔被添加到给定年份的任何日期,以找到该年夏令时的开始,end被添加到该年的任何日期以找到该年度夏令时的结束。

分解:

  • month给你一个四月的日期
  • day会在本月初让你出发
  • weekday=SU(+1)会在指定日期当天或之后为您提供第一个星期日(这是在monthday参数之后应用的,因此当day设置为1时,您将获得当月的第一个星期天)
  • hours=+2-在应用完所有其他内容后,这将给您2个小时的时间。不过,在这种情况下,hour=2可能更适合演示这个概念,因为我认为这些relativedelta的实际使用位置首先去掉了时间部分(在午夜给出日期),所以这实际上是在尝试对2AM进行编码

最新更新