Date Ordinal Output?

后端 未结 14 1753
囚心锁ツ
囚心锁ツ 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: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)
    

提交回复
热议问题