【问题标题】:Javascript date string to python datetime objectJavascript日期字符串到python日期时间对象
【发布时间】:2016-09-04 07:21:23
【问题描述】:

当前的日期时间通过 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.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) 有没有更好的方法来解决它?

【问题讨论】:

    标签: javascript python django datetime


    【解决方案1】:

    您可以使用 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))
    

    【讨论】:

      【解决方案2】:

      您的第一个问题是输入的格式不同。但不幸的是,这不是你唯一的问题,即使你解决了它也不起作用。

      事实上,即使是第一种格式也会因时区不同而失败:

      datetime.strptime("Sun, 04 Sep 2016 07:13:06 IST", "%a, %d %b %Y %H:%M:%S %Z")
      

      失败:

      ValueError: time data 'Sun, 04 Sep 2016 07:13:06 IST' does not match format '%a, %d %b %Y %H:%M:%S %Z'
      

      strptime 不足以处理时区。

      检查这些答案以了解您的选择:

      【讨论】:

        猜你喜欢
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        相关资源
        最近更新 更多