django timezone

정은경·2021년 8월 3일
0
  • DB에는 어쨌든 UTC 기준으로 저장됨!
  • 그런데 django에서 time-zone 설정을 하면, 해당 time-zone 시간을 utc로 알아서 컨버트?해서 쿼리를 수행함
    • 예) 장고 time-zone은 아시아/서울로 설정했을 때
    • 한국서울시간('2021-12-01')에 해당하는 UTC시간(datetime.datetime(2021, 11, 30, 15, 0, tzinfo=))으로 변환?하여 쿼리를 날림
      MonitorDeviceLog.objects.filter(log_date='2021-12-01').all()[0].log_date
      MonitorDeviceLog.log_date received a naive datetime (2021-12-01 00:00:00) while time zone support is active.
      warnings.warn("DateTimeField %s received a naive datetime (%s)"
      datetime.datetime(2021, 11, 30, 15, 0, tzinfo=<UTC>)

DB에는 시간을 UTC 기준으로만 저장하는 이유

The main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen. (The pytz documentation discusses these issues in greater detail.) This probably doesn’t matter for your blog, but it’s a problem if you over-bill or under-bill your customers by one hour, twice a year, every year. The solution to this problem is to use UTC in the code and use local time only when interacting with end users.

USE_TZ = True

When USE_TZ is True, Django still accepts naive datetime objects, in order to preserve backwards-compatibility.
When the database layer receives one, it attempts to make it aware by interpreting it in the default time zone and raises a warning.

Time zone aware input in forms

When you enable time zone support, Django interprets datetimes entered in forms in the current time zone and returns aware datetime objects in cleaned_data.
If the current time zone raises an exception for datetimes that don’t exist or are ambiguous because they fall in a DST transition (the timezones provided by pytz do this), such datetimes will be reported as invalid values.

Time zone aware output in templates

When you enable time zone support, Django converts aware datetime objects to the current time zone when they’re rendered in templates. This behaves very much like format localization.

Reference

profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글