Convert time to human readable text in Python

This Python tutorial to show you how to use the humanize package to convert date time value into human readable string.

Table of contents

  1. Install humanize package
  2. Convert datetime to human readable day month year string
  3. Convert datetime to human readable day month string
  4. Convert datetime to natural representation of time
  5. Convert datetime into natural representation of a timedelta
  6. Convert timedelta to human readable string

Install humanize package

Installing the humanize package using the following command.

pip install humanize

Convert datetime to human readable day month year string

The naturaldate() method of humanize package can be used to convert a datetime value into friendly string in date as the following Python program.

import humanize
import datetime

dt = datetime.datetime(2021, 2, 20)

readable_string = humanize.naturaldate(dt)

print(readable_string)
The program output.
Feb 20 2021

Convert datetime to human readable day month string

The naturalday() method of humanize package to convert a datetime value of string of day month that human readable.

import humanize
import datetime

dt = datetime.datetime(2021, 2, 20)

readable_string = humanize.naturalday(dt)

print(readable_string)
The program output.
Feb 20

Convert datetime to natural representation of time

In the following Python example program, we show you how to use the naturaltime() method to convert datetime value in to a string which in natural representation of time.

import humanize
import datetime

dt = datetime.datetime(2021, 2, 20)

readable_string = humanize.naturaltime(dt)

print(readable_string)
The program output.
9 months ago

Convert datetime into natural representation of a timedelta

We can use the naturaldelta() method to return a natural representation of a timedelta as below.

import humanize
import datetime

now = datetime.datetime.now()
later = now + datetime.timedelta(minutes=30)

readable_string = humanize.naturaldelta(later, when=now)

print(readable_string)
The program output.
30 minutes

Convert timedelta to human readable string

In the following Python program, we use the precisedelta() method to return a precise representation of a time delta.

import humanize
import datetime

delta = datetime.timedelta(seconds=3633, days=2, microseconds=123000)

readable_string1 = humanize.precisedelta(delta)
readable_string2 = humanize.precisedelta(delta, format='%0.4f')
readable_string3 = humanize.precisedelta(delta, minimum_unit='microseconds')
readable_string4 = humanize.precisedelta(delta, suppress=['days'])


print(readable_string1)
print(readable_string2)
print(readable_string3)
print(readable_string4)
The program output.
2 days, 1 hour and 33.12 seconds
2 days, 1 hour and 33.1230 seconds
2 days, 1 hour, 33 seconds and 123 milliseconds
49 hours and 33.12 seconds

Happy Coding 😊