python 格式日期时间,包含“st”、“nd”、“rd”、“th” (英文序数后缀)如 PHP 的“S”

发布于 2024-09-17 21:34:55 字数 726 浏览 4 评论 0原文

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

Thu the 2nd at 4:30

但我在 python 中找不到输出 st, nd, 的方法rdth 就像我可以使用带有 S 字符串的 PHP 日期时间格式(他们称之为“英语序数后缀”)(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 函数都可以。

I would like a python datetime object to output (and use the result in django) like this:

Thu the 2nd at 4:30

But I find no way in python to output st, nd, rd, or th like I can with PHP datetime format with the S string (What they call "English Ordinal Suffix") (http://uk.php.net/manual/en/function.date.php).

Is there a built-in way to do this in django/python? strftime isn't good enough (http://docs.python.org/library/datetime.html#strftime-strptime-behavior).

Django has a filter which does what I want, but I want a function, not a filter, to do what I want. Either a django or python function will be fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

小…楫夜泊 2024-09-24 21:34:55

django.utils.dateformat 有一个函数 format 接受两个参数,第一个是日期(一个 datetime.date [[or datetime.datetime]] 实例,其中 datetime 是Python标准库中的模块),第二个是格式字符串,并返回结果格式化字符串。大写-S 格式项(当然,如果是格式字符串的一部分)是扩展为 'st'、'nd'、'rd' 或 'th' 中正确的一项,取决于相关日期的具体日期。

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.

东京女 2024-09-24 21:34:55

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

def ordinal(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}", ordinal(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')

dont know about built in but I used this...

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

and:

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

dtStylish can be called as follows to get Thu the 2nd at 4:30. Use {th} where you want to put the day of the month ("%d" python format code)

dtStylish(datetime(2019, 5, 2, 16, 30), '%a the {th} at %I:%M')
凶凌 2024-09-24 21:34:55

您可以简单地通过使用 humanize 库来完成此操作

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

然后您可以只给出 ordinal 任何整数,即

ordinal(2)将返回第二

You can do this simply by using the humanize library

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

You can then just give ordinal any integer, ie

ordinal(2) will return 2nd

很快妥协 2024-09-24 21:34:55

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

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]

I've just written a small function to solve the same problem within my own code:

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]
甜尕妞 2024-09-24 21:34:55

我自己的版本。使用python的strftime的格式代码,替换 < code>{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'))

My own version. Use python's strftime's format codes, substituting {th} where you want to see the ordinal suffix.

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)

or

format_date_with_ordinal = lambda d,f: d.strftime(f).replace('{th}', {'1':'st', '2':'nd', '3':'rd'}.get(str(d.day)[-1:], 'th'))
余生一个溪 2024-09-24 21:34:55

这是我使用的东西:

def get_ordinal_suffix(day: int) -> str:
    return {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th') if day not in (11, 12, 13) else 'th'

Here's something that I use:

def get_ordinal_suffix(day: int) -> str:
    return {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th') if day not in (11, 12, 13) else 'th'
天冷不及心凉 2024-09-24 21:34:55

实现@Frosty Snomwan 的方法及其扩展

当我第一次尝试实现Frosty Snowman 的出色答案时,我匆忙地误用了它。他是下面的 ord2 函数。我的“不太好的功能”是ord1。他传递了一个数字。我的需要一根绳子。两者都可以轻松编辑以接收不同的输入类型。我将使用他的函数,但我认为某些代码可能会发现这两个函数的完整“实验”实现很有帮助。

from datetime import datetime


def ord1(n):
    if 4 <= int(n) <= 20 or int(n[-1]) >= 4 or int(n[-1]) == 0:
        return f"{n}th"
    elif int(n[-1]) == 1:
        return f"{n}st"
    elif int(n[-1]) == 2:
        return f"{n}nd"
    elif int(n[-1]) == 3:
        return f"{n}rd"


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


today = datetime.now()
date = today.strftime("%d")
date = ord2(int(date))
full_date_time = today.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
print(full_date_time)

for date in range(1, 32, 1):
    date_ord1 = ord1(str(date))
    date_ord2 = ord2(date)
    print(date_ord1, date_ord2)

输出是

Monday, 21st August 2023 01:33:11 PM
1st 1st
2nd 2nd
3rd 3rd
4th 4th
5th 5th
... all th's ...
20th 20th
21st 21st
22nd 22nd
23rd 23rd
24th 24th
... all th's ...
30th 30th
31st 31st

我最终的功能形式,可能更全面有用的是......

def format_date_time(a_date_time):
    date = a_date_time.strftime("%d")
    d = int(date)
    date = date + (
        "th" if 4 <= d % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
    )
    full_date_time = a_date_time.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
    
    return full_date_time

Implementing @Frosty Snomwan's Method And An Expansion Of It

When I first tried to implement Frosty Snowman's outstanding answer, I misapplied it in my haste. His is the ord2 function below. My "not as good function" is ord1. He passes in a number. Mine takes a string. Both could be easily edited to receive different input types. I will be using his function, but I thought some codes might find the full "experimental" implementation of both helpful.

from datetime import datetime


def ord1(n):
    if 4 <= int(n) <= 20 or int(n[-1]) >= 4 or int(n[-1]) == 0:
        return f"{n}th"
    elif int(n[-1]) == 1:
        return f"{n}st"
    elif int(n[-1]) == 2:
        return f"{n}nd"
    elif int(n[-1]) == 3:
        return f"{n}rd"


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


today = datetime.now()
date = today.strftime("%d")
date = ord2(int(date))
full_date_time = today.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
print(full_date_time)

for date in range(1, 32, 1):
    date_ord1 = ord1(str(date))
    date_ord2 = ord2(date)
    print(date_ord1, date_ord2)

Output is

Monday, 21st August 2023 01:33:11 PM
1st 1st
2nd 2nd
3rd 3rd
4th 4th
5th 5th
... all th's ...
20th 20th
21st 21st
22nd 22nd
23rd 23rd
24th 24th
... all th's ...
30th 30th
31st 31st

I final functional form that might be more overall useful would be ...

def format_date_time(a_date_time):
    date = a_date_time.strftime("%d")
    d = int(date)
    date = date + (
        "th" if 4 <= d % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
    )
    full_date_time = a_date_time.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
    
    return full_date_time
年少掌心 2024-09-24 21:34:55

针对上述问题我得到了以下解决方案:

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

Following solution I got for above problem:

datetime.strptime(mydate, '%dnd %B %Y')
datetime.strptime(mydate, '%dst %B %Y')
datetime.strptime(mydate, '%dth %B %Y')
datetime.strptime(mydate, '%drd %B %Y')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文