如何解决Python 的人性化 timedelta() 告诉我 minimum_unit 是一个无效的参数吗?
我正在尝试打印两个日期之间的大致时差。在此处回答得非常好的问题中: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,17)
4 d2=dt.datetime(2007,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]”
编辑/解决方案:
对不起,我很笨,但我会留下这个问题。如果有人想删除它,没有异议。 MrFuppes 的评论帮助我意识到这主要是由于谷歌没有使用当前版本。确实,在检查 pip list
后,我看到只安装了 0.x 版本,而 3.x 是最新版本。运行 pip install humanize --upgrade
后,我可以使用已接受的答案中建议的 precisedelta
函数。
解决方法
使用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,format="%0.0f")
>>> '4 years,6 months and 6 days'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。