Django时区详解


Posted in Python onJuly 24, 2019

引言

相信使用Django的各位开发者在存储时间的时候经常会遇到这样子的错误:

RuntimeWarning: DateTimeField received a naive datetime while time zone support is active.

这个错误到底是什么意思呢?什么是naive datetime object?什么又是aware datetime object?

在Django配置中如果将settings.TIME_ZONE设置为中国时区(Asia/Shanghai),为什么以下时间函数会得到时间相差较大的结果?

# settings.py
TIME_ZONE = 'Asia/Shanghai'

# python manage.py shell
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2016, 12, 7, 12, 41, 22, 729326)
>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2016, 12, 7, 4, 41, 36, 685921, tzinfo=<UTC>)

接下来笔者将详细揭秘在Django中关于时区的种种内幕,如有不对,敬请指教。

准备

UTC与DST

UTC可以视为一个世界统一的时间,以原子时为基础,其他时区的时间都是在这个基础上增加或减少的,比如中国的时区就为UTC+8。

DST(夏时制)则是为了充分利用夏天日照长的特点,充分利用光照节约能源而人为调整时间的一种机制。通过在夏天将时间向前加一小时,使人们早睡早起节约能源。虽然很多西方国家都采用了DST,但是中国不采用DST。(资料来源:DST 百度百科)

naive datetime object vs aware datetime object

当使用datetime.now()得到一个datetime对象的时候,此时该datetime对象没有任何关于时区的信息,即datetime对象的tzinfo属性为None(tzinfo属性被用于存储datetime object关于时区的信息),该datetime对象就被称为naive datetime object。

>>> import datetime
>>> naive = datetime.datetime.now()
>>> naive.tzinfo
>>>

既然naive datetime object没有关于时区的信息存储,相对的aware datetime object就是指存储了时区信息的datetime object。
在使用now函数的时候,可以指定时区,但该时区参数必须是datetime.tzinfo的子类。(tzinfo是一个抽象类,必须有一个具体的子类才能使用,笔者在这里使用了pytz.utc,在Django中的timezone源码中也实现了一个UTC类以防没有pytz库的时候timezone功能能正常使用)

>>> import datetime
>>> import pytz
>>> aware = datetime.datetime.now(pytz.utc)
>>> aware
datetime.datetime(2016, 12, 7, 8, 32, 7, 864077, tzinfo=<UTC>)
>>> aware.tzinfo
<UTC>

 在Django中提供了几个简单的函数如is_aware, is_naive, make_aware和make_naive用于辨别和转换naive datetime object和aware datetime object。

datetime.now简析

在调用datetime.now()的时候时间是如何返回的呢?在官方文档里只是简单地说明了now函数返回当前的具体时间,以及可以�指定时区参数,并没有具体的说明now函数的实现。

classmethod datetime.now(tz=None)
Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).

If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz's time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(), utcnow().

OK,那么接下来直接从datetime.now()的源码入手吧。

@classmethod
 def now(cls, tz=None):
  "Construct a datetime from time.time() and optional time zone info."
  t = _time.time()
  return cls.fromtimestamp(t, tz)

大家可以看到datetime.now函数通过time.time()返回了一个时间戳,然后调用了datetime.fromtimestamp()将一个时间戳转化成一个datetime对象。

那么,不同时区的时间戳会不会不一样呢?不,时间戳不会随着时区的改变而改变,时间戳是唯一的,被定义为格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

datetime.fromtimestamp

既然时间戳不会随时区改变,那么在fromtimestamp中应该对时间戳的转换做了时区的处理。

直接上源码:

@classmethod
 def _fromtimestamp(cls, t, utc, tz):
  """Construct a datetime from a POSIX timestamp (like time.time()).

  A timezone info object may be passed in as well.
  """
  frac, t = _math.modf(t)
  us = round(frac * 1e6)
  if us >= 1000000:
   t += 1
   us -= 1000000
  elif us < 0:
   t -= 1
   us += 1000000

  converter = _time.gmtime if utc else _time.localtime
  y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
  ss = min(ss, 59) # clamp out leap seconds if the platform has them
  return cls(y, m, d, hh, mm, ss, us, tz)

 @classmethod
 def fromtimestamp(cls, t, tz=None):
  """Construct a datetime from a POSIX timestamp (like time.time()).

  A timezone info object may be passed in as well.
  """
  _check_tzinfo_arg(tz)

  result = cls._fromtimestamp(t, tz is not None, tz)
  if tz is not None:
   result = tz.fromutc(result)
  return result

当直接调用datetime.now()的时候,并没有传进tz的参数,因此_fromtimestamp中的utc参数为False,所以converter被赋值为time.localtime函数。

time.localtime

localtime函数的使用只需要知道它返回一个九元组表示当前的时区的具体时间即可:

def localtime(seconds=None): # real signature unknown; restored from __doc__
 """
 localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
        tm_sec,tm_wday,tm_yday,tm_isdst)

 Convert seconds since the Epoch to a time tuple expressing local time.
 When 'seconds' is not passed in, convert the current time instead.
 """
 pass

笔者觉得更需要注意的是什么因素影响了time.localtime返回的时区时间,那么,就需要谈及time.tzset函数了。

在Python官方文档中关于time.tzset函数解释如下:

time.tzset()

Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.

Availability: Unix.

Note Although in many cases, changing the TZ environment variable may affect the output of functions like localtime() without calling tzset(), this behavior should not be relied on.
The TZ environment variable should contain no whitespace.

可以看到,一个名为TZ的环境变量的设置会影响localtime的时区时间的返回。(有兴趣的同学可以去在Unix下执行man tzset,就知道TZ变量是如何影响localtime了)

最后,笔者给出一些测试的例子,由于获取的时间戳不随时间改变,因此直接调用fromtimestamp即可:

>>> from datetime import datetime
>>> from time import time, tzset
>>> china = datetime.fromtimestamp(time())
>>> import os
>>> os.environ['TZ'] = 'UTC'
>>> tzset()
>>> utc = datetime.fromtimestamp(time())
>>> china
datetime.datetime(2016, 12, 7, 16, 3, 34, 453664)
>>> utc
datetime.datetime(2016, 12, 7, 8, 4, 30, 108349)

以及直接调用localtime的例子:

>>> from time import time, localtime, tzset
>>> import os
>>> china = localtime()
>>> china
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=7, tm_hour=16, tm_min=7, tm_sec=5, tm_wday=2, tm_yday=342, tm_isdst=0)
>>> os.environ['TZ'] = 'UTC'
>>> tzset()
>>> utc = localtime()
>>> utc
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=7, tm_hour=8, tm_min=7, tm_sec=34, tm_wday=2, tm_yday=342, tm_isdst=0)

(提前剧透:TZ这一个环境变量在Django的时区中发挥了重大的作用)

Django TimeZone

timezone.now() vs datetime.now()

笔者在前面花费了大量的篇幅来讲datetime.now函数的原理,并且提及了TZ这一个环境变量,这是因为在Django导入settings的时候也设置了TZ环境变量。

当执行以下语句的时候:

from django.conf import settings

毫无疑问,首先会访问django.conf.__init__.py文件。

在这里settings是一个lazy object,但是这不是本章的重点,只需要知道当访问settings的时候,真正实例化的是以下这一个Settings类。

class Settings(BaseSettings):
 def __init__(self, settings_module):
  # update this dict from global settings (but only for ALL_CAPS settings)
  for setting in dir(global_settings):
   if setting.isupper():
    setattr(self, setting, getattr(global_settings, setting))

  # store the settings module in case someone later cares
  self.SETTINGS_MODULE = settings_module

  mod = importlib.import_module(self.SETTINGS_MODULE)

  tuple_settings = (
   "INSTALLED_APPS",
   "TEMPLATE_DIRS",
   "LOCALE_PATHS",
  )
  self._explicit_settings = set()
  for setting in dir(mod):
   if setting.isupper():
    setting_value = getattr(mod, setting)

    if (setting in tuple_settings and
      not isinstance(setting_value, (list, tuple))):
     raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
    setattr(self, setting, setting_value)
    self._explicit_settings.add(setting)

  if not self.SECRET_KEY:
   raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

  if hasattr(time, 'tzset') and self.TIME_ZONE:
   # When we can, attempt to validate the timezone. If we can't find
   # this file, no check happens and it's harmless.
   zoneinfo_root = '/usr/share/zoneinfo'
   if (os.path.exists(zoneinfo_root) and not
     os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
    raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
   # Move the time zone info into os.environ. See ticket #2315 for why
   # we don't do this unconditionally (breaks Windows).
   os.environ['TZ'] = self.TIME_ZONE
   time.tzset()

 def is_overridden(self, setting):
  return setting in self._explicit_settings

 def __repr__(self):
  return '<%(cls)s "%(settings_module)s">' % {
   'cls': self.__class__.__name__,
   'settings_module': self.SETTINGS_MODULE,
  }

在该类的初始化函数的最后,可以看到当USE_TZ=True的时候(即开启Django的时区功能),设置了TZ变量为settings.TIME_ZONE。

OK,知道了TZ变量被设置为TIME_ZONE之后,就能解释一些很奇怪的事情了。

比如,新建一个Django项目,保留默认的时区设置,并启动django shell:

# settings.py
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# python3 manage.py shell
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 12, 7, 9, 19, 34, 741124)
>>> datetime.datetime.utcnow()
datetime.datetime(2016, 12, 7, 9, 19, 45, 753843)

默认的Python Shell通过datetime.now返回的应该是当地时间,在这里即中国时区,但是当settings.TIME_ZONE设置为UTC的时候,通过datetime.now返回的就是UTC时间。

可以试试将TIME_ZONE设置成中国时区:

# settings.py
TIME_ZONE = 'Asia/Shanghai'

# python3 manage.py shell
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 12, 7, 17, 22, 21, 172761)
>>> datetime.datetime.utcnow()
datetime.datetime(2016, 12, 7, 9, 22, 26, 373080)

此时datetime.now返回的就是中国时区了。

当使用timezone.now函数的时候,情况则不一样,在支持时区功能的时候,该函数返回的是一个带有UTC时区信息的aware datetime obeject,即它不受TIME_ZONE变量的影响。

直接看它的源码实现:

def now():
 """
 Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
 """
 if settings.USE_TZ:
  # timeit shows that datetime.now(tz=utc) is 24% slower
  return datetime.utcnow().replace(tzinfo=utc)
 else:
  return datetime.now()

不支持时区功能,就返回一个受TIME_ZONE影响的naive datetime object。

实践场景

假设现在有这样一个场景,前端通过固定格式提交一个时间字符串供后端的form验证,后端解析得到datetime object之后再通过django orm存储到DatetimeField里面。

Form.DateTimeField

在django关于timezone的官方文档中,已经说明了经过form.DatetimeField返回的在cleaned_data中的时间都是当前时区的aware datetime object。

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.

Models.DatetimeField

在存储时间到MySQL的时候,首先需要知道在Models里面的DatetimeField通过ORM映射到MySQL的时候是什么类型。
笔者首先建立了一个Model作为测试:

# models.py
class Time(models.Model):

 now = models.DateTimeField()

# MySQL Tables Schema
+-------+-------------+------+-----+---------+----------------+
| Field | Type  | Null | Key | Default | Extra   |
+-------+-------------+------+-----+---------+----------------+
| id | int(11)  | NO | PRI | NULL | auto_increment |
| now | datetime(6) | NO |  | NULL |    |
+-------+-------------+------+-----+---------+----------------+

可以看到,在MySQL中是通过datetime类型存储Django ORM中的DateTimeField类型,其中datetime类型是不受MySQL的时区设置影响,与timestamp类型不同。

关于datetime和timestamp类型可以参考这篇文章。

因此,如果笔者关闭了时区功能,却向MySQL中存储了一个aware datetime object,就会得到以下报错:

"ValueError: MySQL backend does not support timezone-aware datetimes. "

关于对时区在业务开发中的一些看法

后端应该在数据库统一存储UTC时间并返回UTC时间给前端,前端在发送时间和接收时间的时候要把时间分别从当前时区转换成UTC发送给后端,以及接收后端的UTC时间转换成当地时区。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python读取ini文件、操作mysql、发送邮件实例
Jan 01 Python
python实现中文输出的两种方法
May 09 Python
Python网络编程使用select实现socket全双工异步通信功能示例
Apr 09 Python
浅谈Pandas中map, applymap and apply的区别
Apr 10 Python
Python查找两个有序列表中位数的方法【基于归并算法】
Apr 20 Python
python3 selenium 切换窗口的几种方法小结
May 21 Python
python创建文件时去掉非法字符的方法
Oct 31 Python
实例详解Python模块decimal
Jun 26 Python
django框架CSRF防护原理与用法分析
Jul 22 Python
pytorch中nn.Conv1d的用法详解
Dec 31 Python
pytorch 改变tensor尺寸的实现
Jan 03 Python
python无序链表删除重复项的方法
Jan 17 Python
详解Django定时任务模块设计与实践
Jul 24 #Python
Python3中urlencode和urldecode的用法详解
Jul 23 #Python
对python3中的RE(正则表达式)-详细总结
Jul 23 #Python
python正则表达式匹配不包含某几个字符的字符串方法
Jul 23 #Python
python使用百度文字识别功能方法详解
Jul 23 #Python
Python使用type关键字创建类步骤详解
Jul 23 #Python
Python安装selenium包详细过程
Jul 23 #Python
You might like
从一个不错的留言本弄的mysql数据库操作类
2007/09/02 PHP
PHP高级OOP技术演示
2009/08/27 PHP
php入门学习知识点六 PHP文件的读写操作代码
2011/07/14 PHP
用mysql_fetch_array()获取当前行数据的方法详解
2013/06/05 PHP
php输入流php://input使用示例(php发送图片流到服务器)
2013/12/25 PHP
php用ini_get获取php.ini里变量值的方法
2015/03/04 PHP
php根据日期或时间戳获取星座信息和生肖等信息
2015/10/20 PHP
php 如何设置一个严格控制过期时间的session
2017/05/05 PHP
在PHP中输出JS语句以及乱码问题的解决方案
2019/02/13 PHP
浅谈PHP封装CURL
2019/03/06 PHP
TNC vs RR BO3 第一场 2.14
2021/03/10 DOTA
Javascript动态绑定事件的简单实现代码
2010/12/25 Javascript
JavaScript中链式调用之研习
2011/04/07 Javascript
javascript读写XML实现广告轮换(兼容IE、FF)
2013/08/09 Javascript
简介JavaScript中的sub()方法的使用
2015/06/08 Javascript
Bootstrap打造一个左侧折叠菜单的系统模板(二)
2016/05/17 Javascript
Select2.js下拉框使用小结
2016/10/24 Javascript
JS敏感词过滤代码
2016/12/23 Javascript
JQuery页面随滚动条动态加载效果的简单实现(推荐)
2017/02/08 Javascript
Vue中的数据监听和数据交互案例解析
2017/07/12 Javascript
Array数组对象中的forEach、map、filter及reduce详析
2018/08/02 Javascript
js对象简介与基本用法示例
2020/03/13 Javascript
Python性能优化的20条建议
2014/10/25 Python
Python中使用asyncio 封装文件读写
2016/09/11 Python
python字符串中的单双引
2017/02/16 Python
Python实现正整数分解质因数操作示例
2018/08/01 Python
Ubuntu下Anaconda和Pycharm配置方法详解
2019/06/14 Python
python操作kafka实践的示例代码
2019/06/19 Python
python 读写excel文件操作示例【附源码下载】
2019/06/19 Python
浅谈numpy中np.array()与np.asarray的区别以及.tolist
2020/06/03 Python
Python Mock模块原理及使用方法详解
2020/07/07 Python
Python unittest discover批量执行代码实例
2020/09/08 Python
Python爬取网站图片并保存的实现示例
2021/02/26 Python
《小白兔和小灰兔》教学反思
2014/02/18 职场文书
法人身份证明书
2015/06/18 职场文书
Pandas数据结构之Series的使用
2022/03/31 Python