1

I can't seem to be able to use the timezones in django. I have read this here but when i try to apply it it won't work.

my model

class Model(models.Model)
    name = models.CharField(max_length=30)
    date = models.DateTimeField()

My view is:

from django.utils.timezone import timezone
def view(request):
    today = datetime.now().replace(tzinfo=utc) 
    model = Model.objects.filter(date__gte=today, date__lte=today + timedelta(days=2)
    return render_to_response('template.html', {'models':model}, context_instance=RequestContext(request)

in my template.html

{%for model in models%}
    {{model.date.hour}}:{{model.date.hour}} - {{model.name}}
{%endfor%}

My settings file

TIME_ZONE = 'Europe/Athens'
USE_TZ = True
USE_L10N = True

So as i read if USE_TZ is true then datetimes are saved in UTC in database, and then django presents them in localtime (according to TIME_ZONE variable) when presenint them in forms.But my template presents the dates as they are saved in the database (meaning two hours behind from localtime e.g i wanted 18:30, it saved 16:30, it shows 16:30). I tried

{%load tz%}
{%for model in models%}
    {{model.date.hour|localtime}}:{{model.date.minute|localtime}} - {{model.name}}
{%endfor%} 

nothing. To be more precise it didn't show any dates at all, it went blank. I tried

{%load tz%}
{%for model in models%}
    {%localtime on %}
        {{model.date.hour}}:{{model.date.time}} - {{model.name}}
    {%endlocaltime%}
{%endfor%} 

But the time remained as is with no modifications.

The thing is that lower in my template i do this in a similar for

{{model.date}} - {{model.name}}

Where it shows the date in the correct timezone(e.g 14:30 becomes 16:30) but not in 24h format (in which i saved it). Can someone help me a bit with timezones and django to clear it once and for all

Rohan
  • 52,392
  • 12
  • 90
  • 87
Apostolos
  • 7,763
  • 17
  • 80
  • 150
  • Please improve the title, it's irrelevent – Infinite Recursion Nov 29 '13 at 09:30
  • Also, what happens if you disable timezone help completely? (i.e. `USE_TZ = False`) – yuvi Nov 29 '13 at 09:34
  • I think `datetime.now().replace(tzinfo=utc)` should be `datetime.utc_now().replace(tzinfo=utc)` i.e using `.utc_now()`. Also what do you mean by - _correct timezone(e.g 14:30 becomes 16:30) but not in 24h format (in which i saved it)_ ? – Rohan Nov 29 '13 at 09:39
  • Model is an example.....just a name @Rohan I mean that I save from my template form with time 16:30 django saves it in db as an aware datetime object like datetime(year=2013, month=11, day=29, hour=14, minute=30....etc) and when i render it in template it renders as 16:30 – Apostolos Nov 29 '13 at 09:47

0 Answers0