pisapapiros
pisapapiros

Reputation: 375

Django datetime field - convert to timezone in view

I have a Django model with a datetime field. When it is saved, the datetime field stored in my DB lose the timezone info, so it's saved as a naive datetime. In general this is not a problem since Django converts it back automatically when rendering the datetime field in the template.

But what about the view? Let's say I need the string representation of the datetime server-side. Depending on summer/winter time, my timezone could be GTM+1 or GMT+2, what makes the things more difficult.

So how do I apply the local tz conversion in the view? I have tried several ways with pytz. No success, ome entries are converted to GMT+1 and others to GMT+2 :(

Eg.

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

Additional info:

Upvotes: 17

Views: 27065

Answers (3)

Shahzaib Akash
Shahzaib Akash

Reputation: 37

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

Upvotes: -1

vsd
vsd

Reputation: 1473

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))

Upvotes: 28

Antony Hatchkins
Antony Hatchkins

Reputation: 33974

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.

Upvotes: 15

Related Questions