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')

查看:57
本文介绍了datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%Z')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是它不起作用.

我做错了什么?

推荐答案

Python 2.7解决方案

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

Solution for Python 2.7

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

显然,即使文档声称相反,引发的错误是 ValueError:'z'是格式为'%Y-%m-%dT%H:%的错误指令M:%S.000%z'.

Apparently, there's no %z in 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'.

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

To solve this, you need to parse the date without timezone first and add the timezone later. Unfortunately you need to subclass tzinfo for that. This answer is based on 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

这篇关于datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%Z')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆