Date Ordinal Output?

后端 未结 14 1641
囚心锁ツ
囚心锁ツ 2020-11-27 06:38

I\'m wondering if there is a quick and easy way to output ordinals given a number in python.

For example, given the number 1, I\'d like to output

相关标签:
14条回答
  • 2020-11-27 07:02

    Not sure if it existed 5 years ago when you asked this question, but the inflect package has a function to do what you're looking for:

    >>> import inflect
    >>> p = inflect.engine()
    >>> for i in range(1,32):
    ...     print p.ordinal(i)
    ...
    1st
    2nd
    3rd
    4th
    5th
    6th
    7th
    8th
    9th
    10th
    11th
    12th
    13th
    14th
    15th
    16th
    17th
    18th
    19th
    20th
    21st
    22nd
    23rd
    24th
    25th
    26th
    27th
    28th
    29th
    30th
    31st
    
    0 讨论(0)
  • 2020-11-27 07:04

    I made a function that seems to work in this case. Just pass in a date object, and it will use the day to figure out the suffix. Hope it helps

    from datetime import date
    def get_day_ordinal(d):
    
        sDay = '%dth'
        if d.day <= 10 or d.day >= 21:
            sDay = '%dst' if d.day % 10 == 1 else sDay
            sDay = '%dnd' if d.day % 10 == 2 else sDay
            sDay = '%drd' if d.day % 10 == 3 else sDay
    
        return sDay % d.day
    
    d = date.today()
    print get_day_ordinal(d)
    
    0 讨论(0)
提交回复
热议问题