Ale*_*ird 17 php python django format datetime
我想要一个python datetime对象输出(并在django中使用结果),如下所示:
Thu the 2nd at 4:30
Run Code Online (Sandbox Code Playgroud)
不过,我觉得没有办法在Python输出st
,nd
,rd
,或th
像我可以用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有一个过滤器可以满足我的需求,但我想要一个功能,而不是过滤器,来做我想要的.一个django或python函数都可以.
Ale*_*lli 25
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.
小智 15
不知道内置但我用这个...
def ord(n):
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
Run Code Online (Sandbox Code Playgroud)
和:
def dtStylish(dt,f):
return dt.strftime(f).replace("{th}", ord(dt.day))
Run Code Online (Sandbox Code Playgroud)
Eds*_*ter 10
我刚刚编写了一个小函数来解决我自己的代码中的相同问题:
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]
Run Code Online (Sandbox Code Playgroud)
小智 6
您只需使用humanize库即可完成此操作
from django.contrib.humanize.templatetags.humanize import ordinal
然后你可以给任意整数,即
ordinal(2)
将返回 2nd
归档时间: |
|
查看次数: |
14095 次 |
最近记录: |