摘自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
中的单数和复数参数之间的其他差异是什么?
答案 0 :(得分: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字符串的行为。您可以看到this 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'
的时区,其中start
relativedelta被添加到给定年份的任何日期以查找该年度的DST开始,end
是添加到指定年份的任何日期以查找该年度的夏令时结束。
打破它:
month
在4月份为您提供日期day
在本月的第一天开始weekday=SU(+1)
为您提供指定日期或之后的第一个星期日(这是在month
和day
参数之后应用的,因此当day
设置为1时,你得到了这个月的第一个星期天)。hours=+2
- 这将在你应用所有其他内容后2小时给你。可能在这种情况下hour=2
对于演示这个概念更有意义,因为这些relativedelta
实际上被使用的地方我认为首先剥掉时间部分(在午夜给出一个日期),所以这是真的想要编码2AM。