python 日期顺序输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/739241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:46:40  来源:igfitidea点击:

Date Ordinal Output?

python

提问by Mez

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

我想知道是否有一种快速简便的方法可以在 python 中输出给定数字的序数。

For example, given the number 1, I'd like to output "1st", the number 2, "2nd", et cetera, et cetera.

例如,给定数字1,我想输出"1st"数字2"2nd"等等,等等。

This is for working with dates in a breadcrumb trail

这是用于在面包屑路径中处理日期

Home >  Venues >  Bar Academy >  2009 >  April >  01 

is what is currently shown

是当前显示的内容

I'd like to have something along the lines of

我想要一些类似的东西

Home >  Venues >  Bar Academy >  2009 >  April >  1st

回答by Abizern

Or shorten David's answer with:

或缩短大卫的回答:

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]

回答by CTT

Here's a more general solution:

这是一个更通用的解决方案:

def ordinal(n):
    if 10 <= n % 100 < 20:
        return str(n) + 'th'
    else:
       return  str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")

回答by alukach

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

不确定 5 年前当您问这个问题时它是否存在,但是inflect包有一个功能可以执行您正在寻找的操作:

>>> 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

回答by Carl

These days I'd use Arrow http://arrow.readthedocs.io/en/latest/(which definately wasn't around in '09)

这些天我会使用 Arrow http://arrow.readthedocs.io/en/latest/(这肯定不在 09 年左右)

>>> import arrow
>>> from datetime import datetime
>>> arrow.get(datetime.utcnow()).format('Do')
'27th'

回答by Vinicius Spader

A more general and shorter solution (as a function):

更通用和更短的解决方案(作为函数):

def get_ordinal(num)
    ldig = num % 10
    l2dig = (num // 10) % 10

    if (l2dig == 1) or (ldig > 3):
        return '%d%s' % (num, 'th')
    else:
        return '%d%s' % (num, {1: 'st', 2: 'nd', 3: 'rd'}.get(ldig))

I just combined David's solutions and libraries (as deegeedubs did). You can even replace the variables (ldig, l2dig) for the real math (since l2dig is used only once), then you get four lines of code.

我只是结合了 David 的解决方案和库(就像 deegeedus 所做的那样)。您甚至可以替换实际数学中的变量 (ldig, l2dig)(因为 l2dig 仅使用一次),然后您会得到四行代码。

回答by eric.frederich

Here it is using dictionaries as either a function or as a lambda...

这里它使用字典作为函数或 lambda ...

If you look at the dictionaries backwards you can read it as...

如果你倒着看字典,你可以把它读成……

Everything ends in 'th'

一切都以'th'结尾

...unless it ends in 1, 2, or 3 then it ends in 'st', 'nd', or 'rd'

...除非以 1、2 或 3 结尾,否则以 'st'、'nd' 或 'rd' 结尾

...unless it ends in 11, 12, or 13 then it ends in 'th, 'th', or 'th'

...除非它以 11、12 或 13 结尾,否则它以“th”、“th”或“th”结尾

# as a function
def ordinal(num):
    return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))

# as a lambda
ordinal = lambda num : '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))

回答by David Z

Except for 1st, 2nd, and 3rd, I think they all just add th... 4th, 5th, 6th, 11th, 21st ... oh, oops ;-)

除了第 1、第 2 和第 3 个,我认为它们都只是添加……第 4、第 5、第 6、第 11、第 21 次……哦,哎呀 ;-)

I think this might work:

我认为这可能有效:

def ordinal(num):
     ldig = num % 10
     l2dig = (num // 10) % 10
     if l2dig == 1:
         suffix = 'th'
     elif ldig == 1:
         suffix = 'st'
     elif ldig == 2:
         suffix = 'nd'
     elif ldig == 3:
         suffix = 'rd'
     else: 
         suffix = 'th'
     return '%d%s' % (num, suffix)

回答by Eric

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)

回答by SwiftsNamesake

def ordinal(n):
    return ["th", "st", "nd", "rd"][n%10 if n%10<4 and not (10<n%100<14) else 0]

回答by Michael Swartz

Here's a function I wrote as part of a calendar type of program I wrote (I'm not including the whole program). It adds on the correct ordinal for any number greater than 0. I included a loop to demo the output.

这是我作为我编写的日历类型程序的一部分编写的函数(我不包括整个程序)。它为大于 0 的任何数字添加正确的序数。我包含了一个循环来演示输出。

def ordinals(num):
    # st, nums ending in '1' except '11'
    if num[-1] == '1' and num[-2:] != '11':
        return num + 'st'
    # nd, nums ending in '2' except '12'
    elif num[-1] == '2' and num[-2:] != '12':
        return num + 'nd'
    # rd, nums ending in '3' except '13'
    elif num[-1] == '3' and num[-2:] != '13':
        return num + 'rd'
    # th, all other nums
    else:
        return num + 'th'

data = ''

# print the first 366 ordinals (for leap year)
for i in range(1, 367):
    data += ordinals(str(i)) + '\n'

# print results to file
with open('ordinals.txt', 'w') as wf:
   wf.write(data)