Python的humanize timedelta()告诉我最小_单位是无效参数?

2024-05-16 15:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在打印两个日期之间的大致时差。在这里回答得很好的问题中:Format timedelta to string给出了几个答案,我可以用其中一个来解决我的问题

然而,我真的很喜欢humanize方法。不幸的是,我无法让它工作,因为documentation中列出的minimum_unit关键字参数给了我一个错误:

import datetime as dt
import humanize as hum
d1=dt.datetime(2003,3,17)
d2=dt.datetime(2007,9,21)
hum.naturaldelta(d2-d1, minimum_unit="days")

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-238c3a390a42> in <module>()
      3 d1=dt.datetime(2003,3,17)
      4 d2=dt.datetime(2007,9,21)
----> 5 hum.naturaldelta(d2-d1, minimum_unit="days")

TypeError: naturaldelta() got an unexpected keyword argument 'minimum_unit'

注意:months=True参数没有帮助,因为它只强制timedelta以月为单位返回,而不是以天为单位返回,当差值小于一年时

你知道我做错了什么吗?(如果这是不可能的,那么我将使用一些变通方法。)

编辑:

我正在使用https://colab.research.google.com/drive/,它似乎运行Python“3.7.10(默认,2021年2月20日,21:17:23)[GCC 7.5.0]”

编辑/解决方案:

对不起,我很愚蠢,但我会留下这个问题。如果有人想移除它,没有人反对。Fuppes先生的评论让我意识到这主要是因为谷歌没有使用当前版本。事实上,在检查了pip list之后,我发现只安装了0.x版本,而3.x是最新版本。在运行pip install humanize --upgrade之后,我能够使用接受的答案中建议的precisedelta函数


Tags: 答案import版本参数datetimeasdtunit
1条回答
网友
1楼 · 发布于 2024-05-16 15:41:04

使用humanfriendly

import datetime
import humanfriendly

d1 = datetime.datetime(2003, 3, 17)
d2 = datetime.datetime(2007, 9, 21)
date_delta = d2 - d1

# there is no month
humanfriendly.format_timespan(date_delta)
>>> '4 years, 27 weeks and 4 days'

或者可能是这样:

from humanize.time import precisedelta

precisedelta(date_delta, minimum_unit='days')
>>> '4 years, 6 months and 5.84 days'
precisedelta(d2-d1, minimum_unit='days', suppress=['months'])
>>> '4 years and 188.84 days'
precisedelta(d2-d1, minimum_unit='days', format="%0.0f")
>>> '4 years, 6 months and 6 days'

相关问题 更多 >