hob*_*es3 3 python django datetime
我注意到默认的Django的datetime作为字符串看起来像这样(来自模板):
April 4, 2012, 6 a.m.
April 14, 2012, 12:06 p.m.
April 14, 2012, midnight
April 14, 2012, noon
April 14, 2012, 6:02 a.m.
Run Code Online (Sandbox Code Playgroud)
请注意日期或时间中没有尾随零.Django也消除了:00分钟,并且还使用字符串"noon"和"midnight"而不是等效的数字时间.
我可以不进行编码的一堆最接近if- elif声明是这样的
# I'm using Django 1.4 with timezone support.
# timezone.now() is the same as `datetime.now()` but it's timezone "aware".
timezone.now().strftime('%B %d, %Y, %I:%M %p').replace( 'AM', 'a.m.' ).replace( 'PM', 'p.m.' )
Run Code Online (Sandbox Code Playgroud)
但这会产生以下结果(使用上面相同的例子)
April 04, 2012, 06:00 a.m.
April 14, 2012, 12:06 p.m.
April 14, 2012, 12:00 a.m.
April 14, 2012, 12:00 p.m.
April 14, 2012, 06:02 a.m.
Run Code Online (Sandbox Code Playgroud)
我需要获取字符串的原因是因为我正在使用ajax(特别是Dajax)所以我必须返回一个字符串,datetime因为我无法在JSON中存储Python对象(即使我可以,JavaScript也不会知道如何解释它).
那么是否有某种Django函数可以转换datetime为Django模板使用的相同字符串?
使用django.utils.dateformatSteven链接到:
>>> import datetime
>>> from django.utils import dateformat
>>> dateformat.format(datetime.datetime.now(), 'F j, Y, P')
u'April 14, 2012, 1:31 p.m.'
Run Code Online (Sandbox Code Playgroud)
P是有趣的扩展strftime,在第93行:
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension.
| 归档时间: |
|
| 查看次数: |
3803 次 |
| 最近记录: |