Is there a way to get Django's default string for date and time from Python's datetime?
datetime, django, python
Solution
Using `django.utils.dateformat` which Steven linked to:
>>> 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` is the interesting extension to `strftime`, on 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.
Problem
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?