I’ve noticed that the default Django’s datetime as a string looks like this (from the template):
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.
Notice how there are no trailing zeros in the date or the time. Also Django eliminates :00 minutes and also uses the string “noon” and “midnight” instead of the equivalent numerical times.
The closest I could get without coding a bunch of if–elif statements is this
# 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.' )
But that would produce the following (using the same example above)
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.
The reason I need to get a string is because I’m using ajax (specifically Dajax) so I have to return a string of datetime since I can’t store a Python object in JSON (even if I could, JavaScript won’t know how to interpret it).
So is there some sort of Django function that can convert datetime into the same string that Django’s template uses?
Using
django.utils.dateformatwhich Steven linked to:Pis the interesting extension tostrftime, on line 93: