[英]Django: How-to convert naive datetime when time zone support is active?
I'm struggeling with Django and datetime. 我在Django和datetime方面苦苦挣扎。
I have a datetime-string as this "Sun, 28 Aug 2016 11:42:00 +0200" - so from my point of view including timezone information "+0200" 我有一个日期时间字符串,例如“ Sun,28 Aug 2016 11:42:00 +0200”-从我的角度来看,包括时区信息“ +0200”
Then I convert it using this: 然后,我将其转换为:
date_published = time.strptime(date_published, "%a, %d %b %Y %H:%M:%S %z")
It gives me this: 它给了我这个:
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=28, tm_hour=11, tm_min=42, tm_sec=0, tm_wday=6, tm_yday=241, tm_isdst=-1)
Then I try to convert it like this: 然后,我尝试将其转换为:
date_published = datetime.fromtimestamp(time.mktime(date_published))
Which gives me: 这给了我:
2016-08-28 11:42:00
And then Django complains when saving it with the following warning: 然后Django在保存它时发出以下警告:
RuntimeWarning: DateTimeField ModelName.field_name received a naive
datetime (2012-01-01 00:00:00) while time zone support is active.
How do I correctly convert the input string so that I can save it into a timezone aware datetime-model's fields? 如何正确转换输入字符串,以便将其保存到可识别时区的datetime-model的字段中?
Best Regeards 最佳后裔
Kev 凯夫
This alone should work: 仅此一项应起作用:
from datetime import datetime
date_published = datetime.strptime(date_published, "%a, %d %b %Y %H:%M:%S %z")
The return I get is datetime.datetime(2016, 8, 28, 11, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
我得到的回报是datetime.datetime(2016, 8, 28, 11, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.