2016-08-18 193 views
1

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

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 

我尝试了强制转换为字符串,像这样:

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。

任何帮助?

+0

你能告诉我们字符串的样子? 'str(excel_ws.Cells(2,4).Value)' – AlexLordThorsen

+0

你有没有考虑过使用'openpyxl'?它不需要安装或自动安装Excel版本,并且可以处理将日期转换为本机Python日期时间的单元格... –

+0

当然。我只是在一个打印声明,这是它看起来像这样: 2016-04-01 17:29:25 + 00:00 现在我感到很傻,因为没有这样做更早。如果总是要在结尾添加一个'+00:00',显然我可以使用一个简单的拼接并获得我需要的。 但是,我仍然想知道是否有更好的方法来处理这个问题。 –

回答

2

所以问题是+00:00时区偏移量。 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' 

一个创可贴的解决方案是剥离时区但是感觉相当毛。

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()) 
+0

谢谢,Alex。 今晚,我刚刚清除了时区。同意,这感觉很糟糕。为了未来(我将继续开发这个),我将研究dateutil。 我讨厌一般的日期/时间问题,所以这可能会有所帮助。 感谢您的研究和解决方案。 –

+0

不客气,祝你好运。 – AlexLordThorsen