当只使用天时,“datetime.timedelta”和“dateutil.relativedelta.relativedelta”有什么区别?

datetime.timedelta (来自Python的标准库)和dateutil.relativedelta.relativedelta之间的区别是什么?

据我所知, timedelta只支持几天(和几周),而relativedelta增加了对以年,月,周或天来定义的期限的支持,并且定义了年,月或日的绝对值。 (请记住,为了这个问题的目的,我不必担心小时,分钟或秒钟)

考虑到我只使用datetime.date对象,并且只对由天数定义的时间段感兴趣, timedeltarelativedelta什么区别? 有什么区别吗?

 from datetime import date, timedelta from dateutil.relativedelta import relativedelta i = -1 # This could have been any integer, positive or negative someday = date.today() # Is there any difference between these two lines? otherday = someday + timedelta(days=i) otherday = someday + relativedelta(days=i) 

dateutil是python标准datetime模块的扩展包。 正如你所说,它提供了额外的function,如timedeltas,以大于一天的单位表示。

如果你不得不问我的女朋友的生日,或者这个月的最后一个星期五,我可以保存多less个月? 这隐藏了由于月份长度不同或者闰年多余天数而导致的复杂计算。

就你而言,你只对天数感兴趣。 所以你最好使用timedelta因为这避免了对dateutil包的额外依赖。

relativedeltatimedelta有更多的参数:

 Definition: relativedelta.relativedelta(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None) 

你可以用它来计算一个月中的最后一个星期五:

 In [14]: import datetime as dt In [15]: import dateutil.relativedelta as relativedelta In [16]: today = dt.date.today() In [17]: rd = relativedelta.relativedelta(day = 31, weekday = relativedelta.FR(-1)) In [18]: today+rd Out[18]: datetime.date(2012, 9, 28)