有没有办法从Python的日期时间获取Django的日期和时间的默认字符串?

时间:2012-04-14 16:18:50

标签: python django datetime

我注意到默认Django的日期时间是一个字符串看起来像这样(来自模板):

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.

注意日期或时间中没有尾随零。 Django也消除了:00分钟,并使用字符串“中午”和“午夜”而不是等效的数字时间。

如果没有编写一堆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.' )

但是这会产生以下结果(使用上面相同的例子)

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.

我需要获取字符串的原因是因为我正在使用ajax(特别是Dajax)所以我返回datetime的字符串,因为我无法存储Python JSON中的对象(即使我可以,JavaScript也不知道如何解释它。)

那么是否有某种Django函数可以将datetime转换为Django模板使用的相同字符串?

2 个答案:

答案 0 :(得分:7)

使用Steven链接到的django.utils.dateformat

>>> import datetime
>>> from django.utils import dateformat
>>> dateformat.format(datetime.datetime.now(), 'F j, Y, P')
u'April 14, 2012, 1:31 p.m.'

Pstrftime上{{1}}的有趣扩展:

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.

答案 1 :(得分:1)

这是一种懒惰的方法:

def f(dt):
    s = dt.strftime('%B %d, %Y, %I:%M %p')
    for unwanted, wanted in [
        ('12:00 AM', 'midnight'),
        ('12:00 PM', 'noon'),
        ('AM','a.m.'),
        ('PM', 'p.m.'),
        (':00', ''),
        (' 0', ' ')]:
        s = s.replace(unwanted, wanted)
    return s

print f(datetime(2012, 4, 4, 6))
print f(datetime(2012, 4, 14, 12, 6))
print f(datetime(2012, 4, 14, 12))
print f(datetime(2012, 4, 14, 0))
print f(datetime(2012, 4, 14, 6, 2))

给出

April 4, 2012, 6 a.m.
April 14, 2012, 12:06 p.m.
April 14, 2012, noon
April 14, 2012, midnight
April 14, 2012, 6:02 a.m.