Year name to century name and decade name in Python

Here are some little helper functions to convert an integer year into a century name and decade name, for example 1989 would be "20th Century" and "1980s".

from math import floor

def year_to_century_name(year: int) -> str:
    century = (floor(int(year) / 100)) + 1
    suffix = ordinal_suffix(century)
    return f"{century}{suffix} Century"


def ordinal_suffix(num: int) -> str:
    return {1: "st", 2: "nd", 3: "rd"}.get(
        0 if 10 > num > 14 else num % 10, "th"
    )


def year_to_decade_name(year: int) -> str:
    decade = floor(int(year) / 10) * 10
    return f"{decade}s"

We use this in Moment Wall Art to extract the century and decade of each piece, which allows for easy taxonomy pages like 20th Century Wall Art or 2020s Wall Art.


View post: Year name to century name and decade name in Python