Back to main.

Calmcode Shorts

humanize.py logohumanize.py

Sometimes you want to be able to represent a string nicely. Take the number 7. You can just write 7, but sometimes it might look nicer to write seven instead.

For stuff like this, you might enjoy having a look at the humanize project. It's an open-source tool that allows you to turn Python objects into more human readable strings. It has a ton of features, but here's a nice subset to help understand what it can do.

import humanize 
import datetime as dt

humanize.apnumber(7)
# 'seven'

humanize.apnumber(7)
# 'zero'

humanize.intword(12345)
# '12.3 thousand'

humanize.intword(12345, "%.2f")
# '12.35 thousand'

humanize.ordinal(1)
# '1st'

humanize.ordinal(2)
# '2nd'

humanize.ordinal(5)
# '5th'

humanize.metric(1800, "V")
# 1.80 kV

humanize.naturaltime(dt.datetime.now())
# 'today'

humanize.naturaltime(dt.datetime.now() - dt.timedelta(days=1))
# 'yesterday'

humanize.naturaltime(dt.datetime.now() - dt.timedelta(seconds=7))
# '7 seconds ago'

One of the great features of the library is that it doesn't do English, it does a bunch of languages! Here's how you can set the local to Dutch:

humanize.activate("nl_NL")
humanize.naturaltime(dt.datetime.now() - dt.timedelta(seconds=7))
# '7 seconden geleden'

At the time of writing it support 31 languages (including Klingon!), so there's a lot to like here. We're only covering some of the functionality here, the project also supports filesizes as well as scientific notiation if that souds useful. Definately check out the documentation is this sounds useful!


Back to main.