dateutil.relativedelta-如何获得以天为单位的持续时间? [英] dateutil.relativedelta - How to get duration in days?

查看:322
本文介绍了dateutil.relativedelta-如何获得以天为单位的持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得以天为单位的相对增量的总持续时间.

I wish to get the total duration of a relativedelta in terms of days.

预期:

dateutil.timedelta(1 month, 24 days) -> dateutil.timedelta(55 days)

我尝试过的事情:

dateutil.timedelta(1 month, 24 days).days -> 24 (WRONG)

有没有简单的方法可以做到这一点?谢谢!

Is there a simple way to do this? Thanks!

推荐答案

这个人也困扰着我.没有一种非常干净的方法来获取特定单位中的时间跨度.这部分是由于日期范围对单位的依赖性.

This one bothered me as well. There isn't a very clean way to get the span of time in a particular unit. This is partly because of the date-range dependency on units.

relativedelta()接受一个月的论证.但是,当您考虑一个月有多长时间时,答案是取决于情况".话虽如此,在技术上不可能将relativedelta()直接转换为几天,而又不知道哪一天三角洲停留在哪一天.

relativedelta() takes an argument for months. But when you think about how long a month is, the answer is "it depends". With that said, it's technically impossible to convert a relativedelta() directly to days, without knowing which days the delta lands on.

这就是我最终要做的.

Here is what I ended up doing.

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

rd = relativedelta(years=3, months=7, days=19)
# I use 'now', but you may want to adjust your start and end range to a specific set of dates.
now = datetime.now()

# calculate the date difference from the relativedelta span
then = now - rd
# unlike normal timedelta 'then' is returned as a datetime
# subtracting two dates will give you a timedelta which contains the value you're looking for
diff = now - then

print diff.days

这篇关于dateutil.relativedelta-如何获得以天为单位的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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