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?
I think you were quite close with the
datetime.datetime.fromtimestamp
. Taking that approach all the way, you could transform yourpywintypes.datetime
object to a timestamp using itstimestamp
method. To be safe with time zones, also use thetzinfo
attribute. SeeIn [4]:
below for the full syntax.I just ran into the same issue when trying to make a pd.DataFrame out of a few rows of an Excel book. I kept getting this terrible Python has stopped working" dialog box.
As a follow up, if you need to check whether or not a cell value is a pywintypes datetime, the following should be good enough.
So the problem is the
+00:00
timezone offset. Looking into this there's not an out of the box solution for PythonOne band-aid solution is to strip the timezone but that feels pretty gross.
Looking around it looks like (if you can use a third party library)
dateutil
solves this issue and is nicer to use thendatetime.strptime
.On Commandline
code
You can try something like this
Pandas has a similar solution using
pd.Timestamp()
Just insert the
pywintype.datetime
object as the argument and setunit =
whatever unit the time stamp is in (Seconds or's'
I think in this case).For a pandas Series I did:
And then:
Adding a simple option for converting pywintypes.datetime to datetime.datetime
By adding any datetime.datetime type to the pywintypes.datetime will result in a cast to the datetime.dateime type. This can be done using a zero-delta for example.
For the case of the original question, the below can be used without requiring additional modules