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:
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With