当前日期时间通过 ajax 请求 传递到 django 后端,它将存储在数据库中。要将其存储在数据库中,必须首先将日期转换为 datetime 对象,这可以为 UTC 格式的日期完成(例如 Sun, 04 Sep 2016 07:13 :06 GMT) 很容易通过以下语句:
>>> from datetime import datetime
>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z")
但是在这种方法中,没有保存用户的时区。
javascript Date 构造函数调用,即 new Date() 返回以下格式的日期:
Sun Sep 04 2016 12:38:43 GMT+0530 (IST)
转换为 datetime 对象时出错。
>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z")
ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z'
1) 如何解决这个问题? 2) 有没有更好的方法来处理它?</p>
请您参考如下方法:
您可以使用 python 的 dateutil 模块来解析您的日期。
from dateutil import parser
parser.parse("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)")
它将输出作为日期时间对象:
datetime.datetime(2016, 9, 4, 7, 13, 6, tzinfo=tzoffset(u'IST', -19800))
