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 the MyModel is 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 now utc", type(now_utc)
print "alaska type", type(alaska)
print "alaska", alaska
# At here i got updated value but when i see inside
# postgres database value is 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
问题: -
将instance.created_at转换为' US / Alaska'输出是2016-02-06 12:42:22.552000-09:00。但是当我将client_date和display_date等同于上面的信号中的alaska时,它没有保存我新更新的阿拉斯加值,而是通过添加5小时来更新client_date和display_date by instance.created_at值。我需要通过阿拉斯加时区更新client_date和display_date。
当我调用instance.save()时,它对postgres数据库没有任何影响。问题是什么?为什么不更新阿拉斯加价值?是否有任何像django强制不更新新值而是使用默认时区更新值?
答案 0 :(得分:0)
时区感知日期时间对象.. 00:00:00+00:00
和.. 01:00:00+01:00
对应于相同的时刻。它们仅以不同方式显示。在Django,a datetime represents a point in time. It’s absolute: it doesn’t depend on anything.
dt = dt.astimezone(whatever_tz)
对数据库中的值没有影响。 The database connection’s time zone is set to UTC(USE_TZ=True
)。如果您需要保留client_date
的时区信息;将它分开存放。