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

时间:2016-08-18 22:12:52

标签: python excel pywin32

我使用pywin32来读/写Excel文件。我在Excel中有一些日期,以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

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

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。

任何帮助?

7 个答案:

答案 0 :(得分:4)

所以问题是+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())

答案 1 :(得分:1)

Pandas使用pd.Timestamp()

也有类似的解决方案

只需插入pywintype.datetime对象作为参数,并设置unit =时间戳的单位(在这种情况下,我认为是秒或's')。

对于熊猫系列,我做到了:

def convert(time):

return pd.Timestamp(time.timestamp(), unit = 's')

然后:

newSeries = oldSeries.apply(convert)

答案 2 :(得分:0)

我认为您与datetime.datetime.fromtimestamp距离很近。完全采用这种方法,您可以使用其pywintypes.datetime方法将timestamp对象转换为时间戳。为了时区安全,还请使用tzinfo属性。有关完整的语法,请参见下面的In [4]:

当我试图从Excel书的几行中制作pd.DataFrame时,我遇到了同样的问题。我一直在收到这个可怕的Python停止工作的对话框。

In [1]: pywindt
Out[1]: pywintypes.datetime(2018, 9, 13, 14, 2, 24, tzinfo=TimeZoneInfo('GMT Standard Time', True))

In [2]: str(pywindt)
Out[2]: '2018-09-13 14:02:24+00:00'

In [3]: # Conversion takes place here!

In [4]: dt = datetime.datetime.fromtimestamp(
   ...:     timestamp=pywindt.timestamp(),
   ...:     tz=pywindt.tzinfo
   ...: )

In [5]: dt
Out[5]: datetime.datetime(2018, 9, 13, 14, 2, 24, tzinfo=TimeZoneInfo('GMT Standard Time', True))

In [6]: str(dt)
Out[6]: '2018-09-13 14:02:24+00:00'

作为后续,如果您需要检查一个单元格值是否为pywintypes日期时间,那么下面的内容就足够了。

In [7]: import pywintypes

In [8]: isinstance(pywindt, pywintypes.TimeType)
Out[8]: True

In [9]: # just out of curiousity

In [10]: isinstance(dt, pywintypes.TimeType)
Out[10]: False

答案 3 :(得分:0)

添加用于将pywintypes.datetime转换为datetime.datetime的简单选项

通过将任何datetime.datetime类型添加到pywintypes.datetime中,将强制转换为datetime.dateime类型。例如,可以使用零增量来完成此操作。

对于原始问题,可以使用以下内容而无需其他模块

desired_datetime_type = excel_ws.Cells(2, 4).Value + datetime.timedelta(0)

答案 4 :(得分:0)

您可以尝试这样的事情

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

答案 5 :(得分:0)

我看到很多使用rstrip的建议。我发现当时间以00结束时将不起作用。

messageConnected()

我建议使用replace

>>> oltime='2020-06-21 19:50:00+00:00'
>>> str(oltime).rstrip("+00:00").strip()
'2020-06-21 19:5'

这是因为rstrip从字符串的左端开始向右移,删除了每个特征的所有instaces:

>>> str(oltime).replace('+00:00', '')
'2020-06-21 19:50:00'
>>> 

答案 6 :(得分:0)

在上述Alex的答案中,如果您使用python 3.8.3rc1和datetime删除了%S和%z之间的空格,那么它将起作用:

>>> import datetime
>>> datetime.datetime.strptime("2016-04-01 17:29:25+00:00", '%Y-%m-%d %H:%M:%S%z')
datetime.datetime(2016, 4, 1, 17, 29, 25, tzinfo=datetime.timezone.utc)
相关问题