使用python/django进行日期时间本地化

api*_*jic 5 python django datetime feedparser

我正在尝试解析RSS提要.Feed中的条目包含以下日期元素:

<dc:date>2016-09-21T16:00:00+02:00</dc:date>
Run Code Online (Sandbox Code Playgroud)

使用feedparser,我尝试:

published_time = datetime.fromtimestamp(mktime(entry.published_parsed))
Run Code Online (Sandbox Code Playgroud)

但问题是我似乎得到了存储在数据库中的错误时间.在这种特殊情况下,日期时间存储为:

2016-09-21 13:00:00
Run Code Online (Sandbox Code Playgroud)

...当我期望14:00 - 正确的UTC时间.

我认为问题出在我们的django设置中,我们有:

TIME_ZONE = 'Europe/Berlin'
Run Code Online (Sandbox Code Playgroud)

因为当我切换到:

TIME_ZONE = 'UTC'
Run Code Online (Sandbox Code Playgroud)

...数据时间存储为正确的UTC时间:

2016-09-21 14:00:00
Run Code Online (Sandbox Code Playgroud)

有没有办法保持django设置不变,但要正确解析和存储这个日期时间,而不会影响django时区设置?

编辑:也许这样更清楚......

print entry.published_parsed
published_time = datetime.fromtimestamp(mktime(entry.published_parsed))
print published_time
localized_time = pytz.timezone(settings.TIME_ZONE).localize(published_time, is_dst=None)
print localized_time

time.struct_time(tm_year=2016, tm_mon=9, tm_mday=21, tm_hour=14, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=265, tm_isdst=0)
2016-09-21 15:00:00
2016-09-21 15:00:00+02:00
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 2

entry.published_parsed无论输入时间字符串是什么,feedparser始终是 utc 时间元组。要获取时区感知datetime对象:

from datetime import datetime

utc_time = datetime(*entry.published_parsed[:6], tzinfo=utc)
Run Code Online (Sandbox Code Playgroud)

其中utc是 tzinfo 对象,例如datetime.timezone.utcpytz.utc,或者只是您的自定义 tzinfo (对于较旧的 python 版本)

您不应该将 utc 时间传递给mktime()需要当地时间的时间。相同的错误:具有正确的 datetime 和正确的 timezone

确保USE_TZ=Truedjango 在任何地方都使用感知的日期时间对象。给定一个时区感知的日期时间对象,django 应该将其正确保存到数据库,无论您的TIME_ZONE或是timezone.get_current_timezone()什么