python格式datetime与"st","nd","rd","th"(英文序数后缀),如PHP的"S"

Ale*_*ird 17 php python django format datetime

我想要一个python datetime对象输出(并在django中使用结果),如下所示:

Thu the 2nd at 4:30
Run Code Online (Sandbox Code Playgroud)

不过,我觉得没有办法在Python输出st,nd,rd,或th像我可以用PHP的日期时间格式S字符串(他们叫什么"英文后缀")(http://uk.php.net/manual/en/function. date.php).

有没有内置的方法在django/python中执行此操作? strftime不够好(http://docs.python.org/library/datetime.html#strftime-strptime-behavior).

Django有一个过滤器可以满足我的需求,但我想要一个功能,而不是过滤器,来做我想要的.一个django或python函数都可以.

Ale*_*lli 25

The django.utils.dateformat has a function format that takes two arguments, the first one being the date (a datetime.date [[or datetime.datetime]] instance, where datetime is the module in Python's standard library), the second one being the format string, and returns the resulting formatted string. The uppercase-S format item (if part of the format string, of course) is the one that expands to the proper one of 'st', 'nd', 'rd' or 'th', depending on the day-of-month of the date in question.


小智 15

不知道内置但我用这个...

def ord(n):
    return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
Run Code Online (Sandbox Code Playgroud)

和:

def dtStylish(dt,f):
    return dt.strftime(f).replace("{th}", ord(dt.day))
Run Code Online (Sandbox Code Playgroud)

  • @Arijoon那部分涵盖了'青少年,这些青少年不遵循与其他一切相同的规则.如果你删除它,当它们应该是"第11"和"第13"时,你将得到"第11"或"第13". (7认同)

Eds*_*ter 10

我刚刚编写了一个小函数来解决我自己的代码中的相同问题:

def foo(myDate):
    date_suffix = ["th", "st", "nd", "rd"]

    if myDate % 10 in [1, 2, 3] and myDate not in [11, 12, 13]:
        return date_suffix[myDate % 10]
    else:
        return date_suffix[0]
Run Code Online (Sandbox Code Playgroud)


小智 6

您只需使用humanize库即可完成此操作

from django.contrib.humanize.templatetags.humanize import ordinal

然后你可以给任意整数,即

ordinal(2) 将返回 2nd