python 用“st"、“nd"、“rd"、“th"格式化日期时间(英文序数后缀)如 PHP 的“S" [英] python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"

查看:100
本文介绍了python 用“st"、“nd"、“rd"、“th"格式化日期时间(英文序数后缀)如 PHP 的“S"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Thu the 2nd at 4:30

但我在 python 中找不到像我一样输出 stndrdth 的方法可以使用带有 S 字符串的 PHP 日期时间格式(他们称之为英文序数后缀")(http://uk.php.net/manual/en/function.date.php).

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

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

Django 有一个过滤器可以做我想做的事,但我想要一个函数而不是过滤器来做我想做的事.django 或 python 函数都可以.

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.

推荐答案

django.utils.dateformat 有一个函数 format 接受两个参数,第一个是日期(一个 datetime.date [[或 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.

这篇关于python 用“st"、“nd"、“rd"、“th"格式化日期时间(英文序数后缀)如 PHP 的“S"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆