【问题标题】:datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%Z')
【发布时间】:2017-01-16 21:06:52
【问题描述】:

我一直在尝试将这种特定的日期格式转换为 Python 中的字符串,如下所示:

datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')

但它不起作用。

我做错了什么?

【问题讨论】:

  • 欢迎来到本站!查看tour"How to ask" 了解更多关于提出问题以吸引高质量答案的信息。请edit your question 显示您收到的输出或错误消息,与您的预期相比。谢谢! 另外,使用直引号'',而不是花引号。

标签: python python-2.7 datetime strptime python-datetime


【解决方案1】:

假设 Python 3,%f 格式可能不是您平台上strptime 的有效格式字符。格式的strptime docs 参考strftime%f 不在the strftime list 中。但是,format string reference 表示

支持的全套格式代码因平台而异,因为 Python 调用平台 C 库的 strftime() 函数,平台变化很常见。

在我的测试系统上,即带有 Py 3.4.5 的 Cygwin,我使用了:

import datetime
datetime.datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%Z')

得到了

ValueError: time data '2017-01-12T14:12:06.000-0500' does not match format '%Y-%m-%dT%H:%M:%S.%f%Z'

我查看了strftime(3) 的手册页,发现我没有%f,而%z 应该是小写的。因此我使用了

datetime.datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.000%z')
#          straight quotes ^ not curly                  ^
#                                                      literal .000 (no %f) ^^^^ 
#                                                                  lowercase %z ^^

并成功解析。

编辑 @Tagc 发现 %f 在 Windows 10 机器上的 PyCharm 中的 Python 3.5 下运行良好。

【讨论】:

  • 这是不正确的。根据文档,%f 是一个有效的格式字符。 docs.python.org/3/library/…
  • @Tagc 这实际上取决于您阅读的文档,事实证明它是特定于平台的。请参阅编辑后的答案。
  • 啊,好吧。我很困惑,所以我会取消投票。 FWIW %f 对我在 Windows 10 机器上的 PyCharm 中的 Python 3.5 下运行良好。
  • @Tagc 谢谢!是的,我很惊讶地发现文档中的内部不一致。感谢您提供额外的数据!
【解决方案2】:

将日期作为输入字符串:

from dateutil import parser
parsed_date = parser.parse(date)

python-transforming-twitter

【讨论】:

    【解决方案3】:

    错误是您使用了%Z 而不是%z。从documentation,您应该使用%z 来匹配例如(empty), +0000, -0400, +1030

    import datetime
    
    result = datetime.datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%z')
    
    print(result)
    

    输出

    2017-01-12 14:12:06-05:00
    

    【讨论】:

    • 问题是我使用的是 python 2.6,它似乎无法识别 %z:
    【解决方案4】:

    如果您没有时区信息,则在 Python 3 中将“%Z”替换为“Z”。

    datetime.strptime('2010-10-04T03:41:22.858Z','%Y-%m-%dT%H:%M:%S.%fZ')
    # datetime.datetime(2010, 10, 4, 3, 41, 22, 858000)
    

    【讨论】:

      【解决方案5】:

      任务:

      “在 Python 中将此特定日期格式转换为字符串”

      import datetime  
      

      解决方案:

      首先修改你的datetime.strptime代码如下:

        obj = datetime.datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%z')
      

      This 是一个有用的站点供您参考,它将帮助您根据自己的喜好修改输出。

      然后使用strftime将其转换为字符串:

      obj.strftime("%b %d %Y %H:%M:%S")
      

      输出:

      'Jan 12 2017 14:12:06'
      

      【讨论】:

        【解决方案6】:

        Python 2.7 解决方案

        从 cmets 中可以看出,OP 需要 Python 2.7 的解决方案。

        显然,python 2.7 的 strptime 中没有 %z,尽管 the documentation claims the contrary,引发的错误是 ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.000%z'

        要解决这个问题,您需要先解析没有时区的日期,然后再添加时区。不幸的是,您需要为此子类化tzinfo。此答案基于this answer

        from datetime import datetime, timedelta, tzinfo
        
        class FixedOffset(tzinfo):
            """offset_str: Fixed offset in str: e.g. '-0400'"""
            def __init__(self, offset_str):
                sign, hours, minutes = offset_str[0], offset_str[1:3], offset_str[3:]
                offset = (int(hours) * 60 + int(minutes)) * (-1 if sign == "-" else 1)
                self.__offset = timedelta(minutes=offset)
                # NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
                # that have the opposite sign in the name;
                # the corresponding numeric value is not used e.g., no minutes
                '<%+03d%02d>%+d' % (int(hours), int(minutes), int(hours)*-1)
            def utcoffset(self, dt=None):
                return self.__offset
            def tzname(self, dt=None):
                return self.__name
            def dst(self, dt=None):
                return timedelta(0)
            def __repr__(self):
                return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
        
        date_with_tz = "2017-01-12T14:12:06.000-0500"
        date_str, tz = date_with_tz[:-5], date_with_tz[-5:]
        dt_utc = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f")
        dt = dt_utc.replace(tzinfo=FixedOffset(tz))
        print(dt)
        

        最后一行打印:

        2017-01-12 14:12:06-05:00
        

        【讨论】:

        • 谢谢@hansaplast 这正是我所需要的,因为我正在使用 Python 的古老版本:P
        • 好吧.. 我不会把 python 2.7 称为古老的,它仍然被那些不想切换到 python 3 的人广泛使用(或者他们的模块还不支持 python 3)
        【解决方案7】:

        如果它是一个字符串,例如从 JSON 文件加载,你可以试试

        date = '2017-01-12T14:12:06.000-0500'
        
        print(date = date[:10]+" "+date[11:19])
        

        返回:

        2017-01-12 14:12:06
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-11-04
          • 2018-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-08
          • 1970-01-01
          相关资源
          最近更新 更多