首先,使用的配置如下
- settings.py
USE_TZ = True
TIME_ZONE = 'Asia/Shanghai'
启用 USE_TZ = True 后,处理时间方面,有两条 “黄金法则”:
- 保证存储到数据库中的是 UTC 时间;
- 在函数之间传递时间参数时,确保时间已经转换成 UTC 时间;
附录
1. 获取时间差异
配置
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
当前北京时间2021-05-11 13:26:34
from datetime import datetime
from django.utils import timezone
def get_now():
print(datetime.now()) # 2021-05-11 13:26:34.519957
print(timezone.now()) # 2021-05-11 05:26:34.520077+00:00