问题
I'm struggeling with Django and 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"
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:
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?
Best Regeards
Kev
回答1:
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)))
回答2:
Python itself can't handle timezones. You need external library to do it. For example dateutil:
from dateutil.parser import parse
dt = parse("Sun, 28 Aug 2016 11:42:00 +0200")
来源:https://stackoverflow.com/questions/39194370/django-how-to-convert-naive-datetime-when-time-zone-support-is-active