python格式的日期时间带有“st”、“nd”、“rd”、“th”(英语序数后缀),类似于PHP的“S”

zhte4eai  于 2022-10-30  发布在  PHP
关注(0)|答案(6)|浏览(383)

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

Thu the 2nd at 4:30

但是我发现在python中没有办法输出stndrdth,就像我可以使用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有一个过滤器,可以做我想做的事情,但是我想要一个函数,而不是过滤器,来做我想做的事情。

rqdpfwrv

rqdpfwrv1#

django.utils.dateformat有一个函数format,该函数有两个参数,第一个参数是日期(一个datetime.datedatetime.datetime示例,其中datetime是Python标准库中的模块),第二个是格式字符串,并返回结果的格式化字符串。大写的-S项(当然,如果是格式字符串的一部分)是一个扩展为“st”、“nd”、“rd”或“th”中适当的一个的字符串,具体取决于所讨论的日期的日期。

kyxcudwk

kyxcudwk2#

不知道内置的,但是我用了这个...

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

dtStylish可以按如下方式调用以获取Thu the 2nd at 4:30。在您要放置月份中的日期的位置使用{th}(“%d”python格式代码)

dtStylish(datetime(2019, 5, 2, 16, 30), '%a the {th} at %I:%M')
9cbw7uwe

9cbw7uwe3#

只需使用人性化库即可完成此操作
ordinal(2)
然后您可以给予序数任意整数,即
ordinal(2)将返回2nd

nszi6y05

nszi6y054#

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

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

o4hqfura5#

我自己的版本。使用python的strftime格式代码,在你想看到序数后缀的地方替换为{th}

def format_date_with_ordinal(d, format_string):
    ordinal = {'1':'st', '2':'nd', '3':'rd'}.get(str(d.day)[-1:], 'th')
    return d.strftime(format_string).replace('{th}', ordinal)

format_date_with_ordinal = lambda d,f: d.strftime(f).replace('{th}', {'1':'st', '2':'nd', '3':'rd'}.get(str(d.day)[-1:], 'th'))
bogh5gae

bogh5gae6#

下面的解决方案我得到了上面的问题:

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

相关问题