2012-04-14 93 views
1

我注意到,默认的Django的日期时间为一个字符串看起来像这样(从模板):有没有办法从Python的日期时间获取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分钟,并使用字符串“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.') 

但是,这将产生以下(使用上述同样的例子)

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,因为我无法在JSON中存储Python对象(即使我如果我能,JavaScript将不知道如何解释它)。

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

+2

或许Django的完成,随着其自身的模块的帮助下格式化:https://code.djangoproject.com/browser/django/trunk/django /utils/dateformat.py – 2012-04-14 16:31:11

回答

7

使用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.' 

P是有趣的扩展到strftime,在line 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. 
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. 
+1

你链接到真正的方式做它,然后不使用它? :) – agf 2012-04-14 17:35:10

+2

@agf:是的,懒。 :) – 2012-04-14 17:44:27

+0

@Steven Rumbalski谢谢,虽然我不想重新发明轮子,但我没有学习一些很酷的列表/元组策略来替换“不需要”的文本。 :-) – hobbes3 2012-04-14 20:09:26