python - Django datetime field not updating using time zone -
setings.py:- use_tz = true time_zone = 'america/chicago' class mymodel(models.model): created_at = models.datetimefield(auto_now_add=true) # time zone related field user_time_zone = models.charfield(max_length=255, null=true, blank=true) time_difference = models.charfield(max_length=255, null=true, blank=true) client_date = models.datetimefield(null=true, blank=true) display_date = models.datetimefield(null=true, blank=true) mymodel object create mymodel.objects.create(user_time_zone=form.cleaned_data['prefer_time_zone']) signal called after mymodel created def update_time_zone(sender, instance, created, **kwargs): if created: fmt = "%y-%m-%d %h:%m:%s %z%z" now_utc = instance.created_at if instance.user_time_zone: if instance.user_time_zone == 'us/alaska': alaska = now_utc.astimezone(timezone('us/alaska')) print "alaska is_aware", is_aware(alaska) print "alaska is_naive", is_naive(alaska) instance.client_date = alaska instance.display_date = alaska instance.time_difference = alaska.strftime(fmt).split(" ")[2] instance.save() print "alaska utc", type(now_utc) print "alaska type", type(alaska) print "alaska", alaska # @ here got updated value when see inside # postgres database value not updated print "instance.client_date", instance.client_date print "us/alaska", alaska.strftime(fmt) signals.post_save.connect(update_time_zone, sender=mymodel) instance.created_at = 2016-02-06 21:42:22.552000+00:00 alaska = 2016-02-06 12:42:22.552000-09:00 issue:-
after converting instance.created_at 'us/alaska' output 2016-02-06 12:42:22.552000-09:00. when make client_date , display_date equal alaska in above signal, not saved newly updated alaska value rather update client_date , display_date instance.created_at value adding 5 hours. need update client_date , display_date alaska time zone.
when calling instance.save() has no effect in postgres database. whats issue? why not updating alaska value? there thing django force not update new value instead update value using default time zone?
timezone-aware datetime objects .. 00:00:00+00:00 , .. 01:00:00+01:00 correspond the same time moment. displayed differently. in django, a datetime represents a point in time. it’s absolute: doesn’t depend on anything.
dt = dt.astimezone(whatever_tz) has no effect on value in database. the database connection’s time zone set utc (use_tz=true). if need preserve client_date's timezone info; store separately.
Comments
Post a Comment