打开 Django 工程的配置文件,可以看到如下配置项:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Asia/Shanghai' # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True
TIME_ZONE 项告诉 Django 应该使用哪个时区
USE_TZ 即让 Django 使用UTC时间
不过这样使用后,我们在做时间比较等操作时必须确保时间已经转换成 UTC 时间。例如计算某篇博客从发布至今已经有多长时间了,之前我并未使用UTC时间,所以采取了如下代码实现:
delta = datetime.datetime.now() - blog.created_time
而因为现在 blog.created_time 是 UTC 时间,从而导致如下错误:
TypeError: can't subtract offset-naive and offset-aware datetimes
既然问题已经知道了,处理起来当然也很简单,那就是转换一下当前时间:
now = datetime.datetime.utcnow().replace(tzinfo=utc)
这样比较就不会有问题了。