[英]Timezone - Make non-UTC datetime timezone aware
我遇到一个CET
日期CET
(通过我的API)的情况,我想将其保存在django
数据库中。
当我这样做时,我总是收到运行时警告:
datetime.fromtimestamp(last_content_update)
当我添加replace
零件时,我没有收到错误,但是我的日期不正确(1h班次):
datetime.fromtimestamp(last_content_update).replace(tzinfo=utc)
知道我该如何加载我的datetime时区吗?
谢谢!
您需要分两步执行此操作:
启用对时区的支持后,Django将UTC中的日期时间信息存储在数据库中。
可以这样完成:
import pytz
from django.utils import timezone
# Convert the naive datetime into a CET datetime
local_datetime = timezone.make_aware(naive_datetime, pytz.timezone('CET'))
# Convert the CET datetime to UTC
utc_datetime = local_datetime.astimezone(timezone.utc)
# Now it can be saved in the database on a model field
MyDateModel.objects.create(title='Another date model',
created=utc_datetime)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.