python:将pywintyptes.datetime转换为datetime.datetime

我正在使用pywin32读取/写入Excel文件。 我在Excel中有一些date,格式为yyyy-mm-dd hh:mm:ss。 我想将它们作为datetime.datetime对象导入到Python中。 这是我开始的代码行:

prior_datetime = datetime.strptime(excel_ws.Cells(2, 4).Value, '%Y-%m-%d %H:%M:%S') 

这没有用。 我得到了错误:

 strptime() argument 1 must be str, not pywintypes.datetime 

我试着把它转换成一个string,就像这样:

 prior_datetime = datetime.strptime(str(excel_ws.Cells(2, 4).Value), '%Y-%m-%d %H:%M:%S') 

那也行不通。 我得到了错误:

 ValueError: unconverted data remains: +00:00 

所以我尝试了一些不同的东西:

 prior_datetime = datetime.fromtimestamp(int(excel_ws.Cells(2, 4).Value)) 

仍然没有运气。 错误:

 TypeError: a float is required. 

投到浮动没有帮助。 也不是整数。 (嘿,我在这一点上绝望了。)

我可能正在寻找错误的plce,但我有一个可怕的时间寻找一般pywin32任何好的文档或特别pywintypes或pywintypes.datetime。

任何帮助?

所以问题是+00:00时区偏移量。 纵观这一点,Python并没有开箱即用的解决scheme

 datetime.datetime.strptime("2016-04-01 17:29:25+00:00", '%Y-%m-%d %H:%M:%S %z') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z' 

一个创可贴的解决scheme是剥离时区,但感觉非常糟糕。

 datetime.datetime.strptime("2016-04-01 17:29:25+00:00".rstrip("+00:00"), '%Y-%m-%d %H:%M:%S') datetime.datetime(2016, 4, 1, 17, 29, 25) 

环顾四周看起来像(如果你可以使用第三方库) dateutil解决这个问题,更好地使用datetime.strptime

在命令行上

 pip install python-dateutil 

 >>> import dateutil.parser >>> dateutil.parser.parse("2016-04-01 17:29:25+00:00") datetime.datetime(2016, 4, 1, 17, 29, 25, tzinfo=tzutc())