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

新手上路,请多包涵

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

 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 字符串(他们称之为“英语序数后缀”)( 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 函数都可以。

原文由 Alexander Bird 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 825
2 个回答

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

原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 2.5 许可协议

不知道内置但我用过这个……

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

原文由 Frosty Snowman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题