Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date_format Django 1.4 with correct timezone

Okay simple question (I think).

I have a DateTime field (auto_add_now) and when output to a template

{{ edited|date:"DATETIME_FORMAT" }}

I get the expected result of "Sept. 16, 2012, 12:01 p.m."

But unfortunately things are slightly more complicated since I am using Backbone.js and need to pass the datetime with JSON, and since it is only used for display purposes I decided to pass it as a nice locale formatted string. So I dug into the code and found what the template tag uses and this is what I setup.

from django.utils.formats import date_format
return {
    'created': date_format(self.created, 'DATETIME_FORMAT'),
}

But that ends up with this "Sept. 16, 2012, 5:01 p.m."

I have a feeling it has to do with the following on the template tag

@register.filter(expects_localtime=True, is_safe=False)

I also tried this but ended up with the same results

from django.utils import timezone
tz = timezone.get_current_timezone()
logger.info(tz)
logger.info(self.edited)
logger.info(format(self.edited, 'DATETIME_FORMAT'))
logger.info(self.edited.replace(tzinfo=tz))
logger.info(format(self.edited.replace(tzinfo=tz), 'DATETIME_FORMAT'))

Which gave me this

INFO: America/Chicago
INFO: 2012-09-16 17:01:52.921276+00:00
INFO: Sept. 16, 2012, 5:01 p.m.
INFO: 2012-09-16 17:01:52.921276-06:00
INFO: Sept. 16, 2012, 5:01 p.m.

So yeah, I must be missing something, and I have been up and down the django documentation and cannot find anything that could point me to what I am doing wrong. Thanks for any help.

like image 741
byoungb Avatar asked Sep 16 '12 20:09

byoungb


1 Answers

I figured it out. And sadly it was in the Django Timezones documentation that I thought I had exhausted. Localize Usage timezone.localtime()

from django.utils.formats import date_format
from django.utils import timezone
date_format(timezone.localtime(page.created), 'DATETIME_FORMAT')
like image 84
byoungb Avatar answered Sep 27 '22 19:09

byoungb