Convert date to human-readable format (tomorrow, 2 days ago) in Python

Question:

I am trying to convert the python date to human-readable format like "tomorrow", "2 days ago", "in a week", etc.

I can write some snippets like below, but is there any python package available for the same? I found the dateperser package to parse the human-readable format to date object, but not the other way.

Thanks.

from datetime import date, timedelta

today = date.today()

for d in range(-10, 10, 1):
    next = today + timedelta(days=d)
    diff = (next - today).days

    if diff == 0:
        s = "Today"
    elif diff == -1:
        s = "Yesterday"
    elif diff == 1:
        s = "Tomorrow"
    elif diff == 2:
        s = "Day after Tomorrow"
    elif abs(diff) < 4:
        s = f"{abs(diff)} days ago" if diff < 0 else f"In {abs(diff)} days"
    elif abs(diff) <= 7:
        str = "Last" if diff < 0 else "Next"
        day = next.strftime("%A")
        s = f"{str} {day}"
    else:
        day = next.strftime("%d-%m-%Y")
        s = f"On {day}"

    print(f"{next} ({d}): {s}")

Output:

2021-09-09 (-10): On 09-09-2021
2021-09-10 (-9): On 10-09-2021
2021-09-11 (-8): On 11-09-2021
2021-09-12 (-7): Last Sunday
2021-09-13 (-6): Last Monday
2021-09-14 (-5): Last Tuesday
2021-09-15 (-4): Last Wednesday
2021-09-16 (-3): 3 days ago
2021-09-17 (-2): 2 days ago
2021-09-18 (-1): Yesterday
2021-09-19 (0): Today
2021-09-20 (1): Tomorrow
2021-09-21 (2): Day after Tomorrow
2021-09-22 (3): In 3 days
2021-09-23 (4): Next Thursday
2021-09-24 (5): Next Friday
2021-09-25 (6): Next Saturday
2021-09-26 (7): Next Sunday
2021-09-27 (8): On 27-09-2021
2021-09-28 (9): On 28-09-2021
Asked By: ujjaldey

||

Answers:

Yes, You can use humanize, It has different set of APIs for Date & time humanization

>>> import humanize
>>> import datetime as dt
>>> humanize.naturalday(dt.datetime.now())
'today'
>>> humanize.naturaldelta(dt.timedelta(seconds=1001))
'16 minutes'
>>> humanize.naturalday(dt.datetime.now() - dt.timedelta(days=1))
'yesterday'
>>> humanize.naturaltime(dt.datetime.now() - dt.timedelta(seconds=1))
'a second ago'

You can also use precisedelta API to get more accurate representation of your delta.

>>> import humanize
>>> import datetime as dt
>>> delta = dt.timedelta(seconds=3633, days=2, microseconds=123000)
>>> humanize.precisedelta(delta)
'2 days, 1 hour and 33.12 seconds'
>>> humanize.precisedelta(delta, minimum_unit="microseconds")
'2 days, 1 hour, 33 seconds and 123 milliseconds'
>>> humanize.precisedelta(delta, suppress=["days"], format="%0.4f")
'49 hours and 33.1230 seconds'

API reference documentation can be find here.

Answered By: Abdul Niyas P M
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.