RSS Feed中的pubDate格式为:
2011-12-19T01:56:28-06:00
2011-10-19T06:11:02 + 00:00
如何将其转换为公共时区,以便将其存储在db.DateTimeProperty()中并按日期对项目进行排序,而不考虑时区?
答案 0 :(得分:3)
这是ISO8601日期时间格式的变体。这是我解析日期的函数:
from datetime import datetime, timedelta
def parse_iso8601_datetime(dtstr, loose=False):
"""
Convert ISO8601 datetime string and return Python datetime.datetime.
Specify loose=True for more relaxed parsing accepting eg "YYYY-MM-DD" format.
Raise ValueError on malformed input.
"""
dt = None
if len(dtstr) == 19: # (eg '2010-05-07T23:12:51')
dt = datetime.strptime(dtstr, "%Y-%m-%dT%H:%M:%S")
elif len(dtstr) == 20: # (eg '2010-05-07T23:12:51Z')
dt = datetime.strptime(dtstr, "%Y-%m-%dT%H:%M:%SZ")
elif len(dtstr) == 25: # (eg '2010-05-07T23:12:51-08:00')
dt = datetime.strptime(dtstr[0:19], "%Y-%m-%dT%H:%M:%S")
tzofs = int(dtstr[19:22])
dt = dt - timedelta(hours=tzofs)
else:
if loose:
if len(dtstr) == 10: # (eg '2010-05-07')
dt = datetime.strptime(dtstr, "%Y-%m-%d")
if not dt:
raise ValueError("Invalid ISO8601 format: '%s'" % dtstr)
return dt