python dateutil.relativedelta,“datetime.timedelta”之间的区别是什么和“dateutil.relativedelta.relativedelta”当工作...

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

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)

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 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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值