[Fixed]-Django datetime field – convert to timezone in view

28👍

start with this:

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, pytz.timezone('Europe/Berlin'))

To convert to UTC+1:

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, timezone.get_fixed_timezone(60))
👤vsd

14👍

There’s no need to use django.utils to convert between timezones :

berlin = pytz.timezone('Europe/Berlin')
local_dt = item.created_at.astimezone(berlin)

Yet if you usually work with just one timezone it is convenient to store it in settings.TIME_ZONE = 'Europe/Berlin' and then

local_dt = timezone.localtime(item.created_at)

will convert it to your localtime.

-1👍

django provides timesince function in django.utils.timesince module

i use this

from django.utils.timesince import timesince
since = a_datetime_object
return timesince(since)

you can also pass a second argument to be a reference instead of datetime.now()

Possible outputs are
"2 weeks, 3 days" and "1 year, 3 months" etc

Leave a comment