Python 在';dateutil.relativedelta.relativedelta';?
摘自对 年、月、日、时、分、秒、微秒:Python 在';dateutil.relativedelta.relativedelta';?,python,python-dateutil,relativedelta,Python,Python Dateutil,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 va
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'
的时区,其中开始
相对延迟被添加到给定年份的任何日期以查找该年份的DST开始,而结束
被添加到给定年份的任何日期以查找该年份的DST结束
细分:
为您提供四月的日期month
从月初开始day
为您提供指定日期当天或之后的第一个星期日(这在weekday=SU(+1)
和月
参数之后应用,因此当日
设置为1时,您将获得该月的第一个星期日)日
-这将在应用所有其他内容后给你2个小时的时间。在这种情况下,hours=+2
可能更适合演示这个概念,但是,因为这些hours=2
s实际上在哪里被使用,我认为首先去掉了时间部分(在午夜给出日期),所以这是真正的尝试编码凌晨2点relativedelta