gpt4 book ai didi

python - dateutil.relativedelta - 如何获得以天为单位的持续时间?

转载 作者:太空狗 更新时间:2023-10-29 18:28:52 26 4
gpt4 key购买 nike

我希望获得以天为单位的 relativedelta 的总持续时间。

预期:

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

我尝试过的:

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

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

最佳答案

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

relativedelta() 需要几个月的争论。但是当您考虑一个月有多长时,答案是“视情况而定”。话虽如此,技术上不可能将 relativedelta() 直接转换为天数,而不知道 哪些 时间差值。

这是我最后做的。

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

关于python - dateutil.relativedelta - 如何获得以天为单位的持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com