I am trying to print the approximate time difference between two dates. In the really well answered question here: Format timedelta to string several answers were given, and I can use one of those to solve my issue.
However, I really liked the humanize
approach. Unfortunately I can not get it to work, since the minimum_unit
keyword argument, which is listed in the documentation, gives me an error:
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'
Note: the months=True
argument doesnt help, because it only forces the timedelta to be returned in months instead of days, when the difference is below one year.
Any ideas what I am doing wrong? (If this is just not possible, then I will use some workaround.)
EDIT:
I am using https://colab.research.google.com/drive/, which seems to run Python "3.7.10 (default, Feb 20 2021, 21:17:23) [GCC 7.5.0]"
EDIT/SOLUTION:
Sorry, I was stupid, but I will leave the question. If someone wants to remove it, no objections. The comment by MrFuppes helped me realize that it was mostly due to Google not using the current version. Indeed, after checking with pip list
, I saw that only 0.x version was installed, while 3.x was current. After running pip install humanize --upgrade
I was able to use the precisedelta
function suggested in the accepted answer.
Use 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'
Or maybe this:
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'