“datetime.timedelta”之间的区别是什么和“dateutil.relativedelta.relativedelta”当工作只有几天? [英] What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days?

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

问题描述

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

What is the difference between datetime.timedelta (from Python's standard library) and dateutil.relativedelta.relativedelta when working only with days?

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

As far as I understand, timedelta only supports days (and weeks), while relativedelta adds support for periods defined in terms of years, months, weeks or days, as well as defining absolute values for year, month or day. (remember, for the purposes of this question, I don't have to worry about hours, minutes or seconds)

考虑到我' m只使用 datetime.date 对象,只对天数定义的期间感兴趣, 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”当工作只有几天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆