日期时间和相对delta的奇怪算法



relativedelta对象相乘是否安全?我看到了一些奇怪和不一致的行为,并且找不到这个类支持哪种算法的文档(如果有的话)

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> datetime.now() + relativedelta(days=2)
datetime.datetime(2014, 5, 30, 12, 24, 59, 173941)
>>> datetime.now() + relativedelta(days=1) * 2
# TypeError: integer argument expected, got float
另一方面:
>>> relativedelta(days=2) == relativedelta(days=1) * 2
True

完整回溯(python 2.7.5和dateutil 1.5):

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/dateutil/relativedelta.py", line 261, in __radd__
    day = min(calendar.monthrange(year, month)[1],
  File "/usr/lib/python2.7/calendar.py", line 121, in monthrange
    day1 = weekday(year, month, 1)
  File "/usr/lib/python2.7/calendar.py", line 113, in weekday
    return datetime.date(year, month, day).weekday()
TypeError: integer argument expected, got float

您遇到了relativedelta处理乘法的已知错误,自修复以来。它只影响Python 2.7或更新版本(某些函数的调用签名被收紧)。

升级python-dateutils包到2.1或更新版本。

不要被项目文档中2.0-is-Python-3-only的错误信息吓倒;2.1和2.2是Python 2和3的交叉兼容。

相关内容

  • 没有找到相关文章

最新更新