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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41684991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:26:22  来源:igfitidea点击:

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

pythonpython-2.7datetimestrptimepython-datetime

提问by mrjextreme6

I've been trying to convert this specific date format to a string in Python like so:

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

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

But it doesn't work.

但它不起作用。

What am I doing wrong?

我究竟做错了什么?

回答by Tagc

The error was that you used %Zinstead of %z. From the documentation, you should use %zto match e.g. (empty), +0000, -0400, +1030

错误是您使用了%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)

Output

输出

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

回答by ade1e

Task:

任务:

"convert this specific date format to a string in Python"

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

import datetime  

Solution:

解决方案:

First modify your datetime.strptimecode as follows:

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

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

Thisis a useful site for your reference and will help you modify the output as per your preference.

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

Then use strftimeto convert it to a string:

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

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

Out:

出去:

'Jan 12 2017 14:12:06'

回答by hansaplast

Solution for Python 2.7

Python 2.7 的解决方案

From the comments it became clear that OP needs a solution for Python 2.7.

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

Apparently, there's no %zin strptime for python 2.7 even though the documentation claims the contrary, the raised error is ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.000%z'.

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

To solve this, you need to parse the date without timezone first and add the timezone later. Unfortunately you need to subclass tzinfofor that. This answer is based on this answer

要解决这个问题,您需要先解析没有时区的日期,然后再添加时区。不幸的是,您需要为此进行子类化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)

The last line prints:

最后一行打印:

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

回答by ericson.cepeda

Having date as the input str:

将日期作为输入字符串:

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

python-transforming-twitter

蟒蛇转换推特

回答by cxw

Assuming Python 3, the format %fmay not be a valid format character for strptimeon your platform. The strptimedocsreference strftimefor the formats, and %fisn't in the strftimelist. However, the format string referencesays that

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

The full set of format codes supported varies across platforms, because Python calls the platform C library's strftime() function, and platform variations are common.

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

On my test system, which is Cygwin with Py 3.4.5, I used:

在我的测试系统(带有 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')

and got

并得到

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

I checked the man pages for strftime(3)and found that I don't have %f, and %zshould be lowercase. I therefore used

我检查了手册页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 ^^

and got a successful parse.

并成功解析。

Edit@Tagc found that %fworked fine running under Python 3.5 in PyCharm on a Windows 10 machine.

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

回答by Priya Venky

If you don't have timezone information, replacing the '%Z' with 'Z' works in Python 3.

如果您没有时区信息,则在 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)

回答by NumberVII

if it is a string, e.g. load from a JSON file, you can try

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

date = '2017-01-12T14:12:06.000-0500'

print(date = date[:10]+" "+date[11:19])

returns:

返回:

2017-01-12 14:12:06