Python DateTimeField 收到了一个天真的日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21038881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DateTimeField received a naive datetime
提问by DoNotArrestMe
I have model with DateTimeFieldcolumn.
我有DateTimeField列的模型。
I'm try to insert row with database current_timevalue directly into table by sql query.
我尝试通过 sql 查询将具有数据库current_time值的行直接插入表中。
My sql query for MySQL database like:
我对 MySQL 数据库的 sql 查询如:
INSERT INTO MyTable (..., my_datetime, ...) VALUES (..., current_time, ...)
And get:
并得到:
RuntimeWarning: DateTimeField ModelName.field_name received a naive datetime (2014-01-09 22:16:23) while time zone support is active.
RuntimeWarning:DateTimeField ModelName.field_name 在时区支持处于活动状态时收到了一个朴素的日期时间 (2014-01-09 22:16:23)。
How to insert current time directly into table by sql query without warning?
如何在没有警告的情况下通过sql查询将当前时间直接插入表中?
回答by falsetru
Use django.utils.timezone.nowinstead of datetime.datetime.now.
使用django.utils.timezone.now代替datetime.datetime.now。
from django.utils import timezone
current_time = timezone.now()
回答by hellsgate
Further to falsetru's answer, if the datetime has already been created you can convert it to timezone aware:
除了 falsetru 的回答之外,如果已经创建了日期时间,您可以将其转换为时区感知:
from django.utils import timezone
my_datetime = timezone.make_aware(my_datetime, timezone.get_current_timezone())
回答by J0ANMM
You can also make the datetime time zone aware with localizefrom pytz, as explained here.
您也可以使日期时间时区知道与localize从pytz作为解释在这里。
UTC:
世界标准时间:
import pytz
dt_aware = pytz.utc.localize(dt_naive)
Any other time zone:
任何其他时区:
import pytz
tz = 'Europe/Berlin' #or whaterver timezone you want
dt_aware = pytz.timezone(tz).localize(dt_naive)
And herethe list of timezones.
而这里的时区的列表。

