datetime.strptime( '2017-01-12T14:12:06.000-0500', '%Y-%间 - %的dT%H:%M:%S%F%Z')

mrj*_*me6 1 python datetime strptime python-2.7 python-datetime

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

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

但它不起作用.

我究竟做错了什么?

Tag*_*agc 9

错误是您使用%Z而不是%z.从文档中,您应该使用%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)
Run Code Online (Sandbox Code Playgroud)

产量

2017-01-12 14:12:06-05:00
Run Code Online (Sandbox Code Playgroud)


cxw*_*cxw 6

假设使用 Python 3,该格式%f可能不是strptime您平台上的有效格式字符。格式的文档strptime参考,不在列表。但是,格式字符串参考strftime%fstrftime

\n\n
\n

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

\n
\n\n

在我的测试系统(Cygwin with Py 3.4.5)上,我使用了:

\n\n
import datetime\ndatetime.datetime.strptime(\'2017-01-12T14:12:06.000-0500\',\'%Y-%m-%dT%H:%M:%S.%f%Z\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

并得到了

\n\n
ValueError: time data \'2017-01-12T14:12:06.000-0500\' does not match format \'%Y-%m-%dT%H:%M:%S.%f%Z\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

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

并获得成功的解析。

\n\n

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

\n


han*_*ast 3

Python 2.7 的解决方案

从评论中可以清楚地看出,OP 需要一个针对 Python 2.7 的解决方案。

显然,Python 2.7 的 strptime 中没有%z,尽管文档声称相反,但引发的错误是ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.000%z'

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

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)
Run Code Online (Sandbox Code Playgroud)

最后一行打印:

2017-01-12 14:12:06-05:00
Run Code Online (Sandbox Code Playgroud)