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

2024-04-26 21:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但没用。

我做错什么了?


Tags: 字符串datetime格式strptime
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

Python2.7解决方案

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

显然,python 2.7的strtime中没有%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

任务:

“将此特定日期格式转换为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'

相关问题 更多 >