Search code examples
pythonexcelpywin32

python: convert pywintyptes.datetime to datetime.datetime


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

Still no luck. Error:

TypeError: a float is required.

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

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.

Any help?


Solution

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

    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.

    On Commandline

    pip install python-dateutil
    

    code

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