本文介绍了“datetime.timedelta”之间的区别是什么和“dateutil.relativedelta.relativedelta”当工作只有几天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(来自Python的标准库)和对象,只对天数定义的期间感兴趣, timedelta relativedelta 之间有什么区别?有没有什么区别?

Considering that I'm only working with datetime.date objects, and only interested in periods defined by the number of days, what's the difference between timedelta and relativedelta? Is there any difference?

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 模块。正如你所说,它提供了额外的功能,如timedeltas表示为大于一天的单位。

dateutil is an extension package to the python standard datetime module. As you say, it provides extra functionality, such as timedeltas that are expressed in units larger than a day.

如果你必须提出问题,如多少我的女朋友的生日可以保存几个月,还是这个月的最后一个星期五?这隐藏了由不同长度的月份引起的复杂计算,或者是闰年的额外天数。

This is useful if you have to ask questions such as how many months can I save before my girlfriend's birthday comes up, or what's the last Friday in the month? This hides complex calculations that are caused by the different lengths of the months, or extra days in leap years.

在您的情况下,您只对天数感兴趣。所以最好使用 timedelta ,因为这样可以避免对 dateutil 包的额外依赖。

In your case, you are only interested in the number of days. So you'd best use timedelta as this avoids an extra dependency on the dateutil package.

这篇关于“datetime.timedelta”之间的区别是什么和“dateutil.relativedelta.relativedelta”当工作只有几天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:29