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')
我一直在尝试将此特定日期格式转换为 Python 中的字符串,如下所示:
datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')
但是没用。
我做错了什么?
假设 Python 3,格式 %f
在您的平台上可能不是 strptime
的有效格式字符。 strptime
docs reference strftime
for the formats, and %f
isn't in the strftime
list. However, the format string reference 表示
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.
在我的测试系统上,即带有 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 ^^
并成功解析。
Edit @Tagc 发现 %f
在 PyCharm PyCharm 下 运行 工作正常 运行 =] 10台机器。
错误是您使用了 %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
任务:
"convert this specific date format to a string in 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'
Python 2.7
的解决方案
从评论中可以清楚地看出,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
将日期作为输入字符串:
from dateutil import parser
parsed_date = parser.parse(date)
如果您没有时区信息,用 'Z' 替换 '%Z' 可以在 Python 3.
datetime.strptime('2010-10-04T03:41:22.858Z','%Y-%m-%dT%H:%M:%S.%fZ')
# datetime.datetime(2010, 10, 4, 3, 41, 22, 858000)
如果它是一个字符串,例如从 JSON 文件加载,您可以尝试
date = '2017-01-12T14:12:06.000-0500'
print(date = date[:10]+" "+date[11:19])
returns:
2017-01-12 14:12:06
我一直在尝试将此特定日期格式转换为 Python 中的字符串,如下所示:
datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')
但是没用。
我做错了什么?
假设 Python 3,格式 %f
在您的平台上可能不是 strptime
的有效格式字符。 strptime
docs reference strftime
for the formats, and %f
isn't in the strftime
list. However, the format string reference 表示
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.
在我的测试系统上,即带有 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 ^^
并成功解析。
Edit @Tagc 发现 %f
在 PyCharm PyCharm 下 运行 工作正常 运行 =] 10台机器。
错误是您使用了 %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
任务:
"convert this specific date format to a string in 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'
Python 2.7
的解决方案从评论中可以清楚地看出,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
将日期作为输入字符串:
from dateutil import parser
parsed_date = parser.parse(date)
如果您没有时区信息,用 'Z' 替换 '%Z' 可以在 Python 3.
datetime.strptime('2010-10-04T03:41:22.858Z','%Y-%m-%dT%H:%M:%S.%fZ')
# datetime.datetime(2010, 10, 4, 3, 41, 22, 858000)
如果它是一个字符串,例如从 JSON 文件加载,您可以尝试
date = '2017-01-12T14:12:06.000-0500'
print(date = date[:10]+" "+date[11:19])
returns:
2017-01-12 14:12:06