python:将pywintyptes.datetime转换为datetime.datetime [英] python: convert pywintyptes.datetime to datetime.datetime

查看:153
本文介绍了python:将pywintyptes.datetime转换为datetime.datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using pywin32 to read/write to an Excel file. I have some dates in Excel, stored in format yyyy-mm-dd hh:mm:ss. I would like to import those into Python as datetime.datetime objects. Here is the line of code I started with:

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

那没有用.我收到错误消息:

That didn't work. I got the error:

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

我试图将其转换为字符串,如下所示:

I tried casting it to a string, like so:

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

那也不起作用.我得到了错误:

That didn't work either. I got the error:

ValueError: unconverted data remains: +00:00

所以我尝试了一些不同的方法:

So then I tried something a little different:

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

仍然没有运气.错误:

TypeError: a float is required.

强制浮动没有帮助.也不是整数.(嘿,我现在很绝望.)

Casting to a float didn't help. Nor integer. (Hey, I was desperate at this point.)

我可能在寻找错误的地方,但是我很难找到关于pywin32的任何常规文档,尤其是pywintypes或pywintypes.datetime.

I might be looking in the wrong plce, but I'm having a terrible time finding any good documentation on pywin32 in general or pywintypes or pywintypes.datetime in particular.

有帮助吗?

推荐答案

所以问题出在 +00:00 时区偏移.为此,没有针对Python的现成解决方案

So the problem is the +00:00 timezone offset. Looking into this there's not an out of the box solution for Python

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'

一个创可贴解决方案是剥离时区,但是感觉很麻烦.

One band-aid solution is to strip the timezone but that feels pretty gross.

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 更好地使用.

Looking around it looks like (if you can use a third party library) dateutil solves this issue and is nicer to use then 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())

这篇关于python:将pywintyptes.datetime转换为datetime.datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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