代码之家  ›  专栏  ›  技术社区  ›  Alexander Bird

python格式的datetime,带有“st”、“nd”、“rd”、“th”(英文序数后缀),类似于PHP的“s”

  •  16
  • Alexander Bird  · 技术社区  · 14 年前

    我希望python datetime对象输出(并在django中使用结果)如下:

    Thu the 2nd at 4:30
    

    但是我在python中找不到输出的方法 st nd rd ,或 th 就像我可以用PHP的datetime格式 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函数都可以。

    6 回复  |  直到 12 年前
        1
  •  30
  •   Alex Martelli    14 年前

    django.utils.dateformat format 这需要两个参数,第一个是日期(a) datetime.date datetime.datetime datetime S 格式项(当然,如果是格式字符串的一部分)是扩展到“st”、“nd”、“rd”或“th”的正确项,具体取决于所讨论日期的月份。

        2
  •  18
  •   Arvind Sridharan    4 年前

    不知道内置,但我用这个。。。

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

    以及:

    def dtStylish(dt,f):
        return dt.strftime(f).replace("{th}", ord(dt.day))
    

    Thu the 2nd at 4:30 . 使用 {th} 要将月份的日期(“%d”)放在何处 python format code )

    dtStylish(datetime(2019, 5, 2, 16, 30), '%a the {th} at %I:%M')
    
        3
  •  9
  •   Adrian Krige    7 年前

    您只需使用“人性化”库就可以做到这一点

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

    你就可以给序数任何整数,即

    ordinal(2) 会回来的 2nd

        4
  •  3
  •   Edster    6 年前

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

    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]
    
        5
  •  -1
  •   Gwendal Delisle Arnold    8 年前

    def date_extention(number):
        if number%10 == 1:
            return '%dst' % number
        if number%10 == 2:
            return '%dnd' % number
        if number%10 == 3:
            return '%drd' % number
        if (number%10 >= 4) or (number%10== 0):
            return '%dth' % number
    

    顺便说一下,这适用于任何数字,所以我建议你做一个模块了。尤其是如果你做了很多用户输入的程序。。。

        6
  •  -1
  •   Tyl    5 年前

    以下是我对上述问题的解决方案:

    datetime.strptime(mydate, '%dnd %B %Y')
    datetime.strptime(mydate, '%dst %B %Y')
    datetime.strptime(mydate, '%dth %B %Y')
    datetime.strptime(mydate, '%drd %B %Y')