views:

64

answers:

2

I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is:

07/06/10 00:00:00

I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). However, after some playing around I realized that it is not being pulled as a string... Running type() on it returns <type 'time'> .

I then assumed that it was a Python time object, and tried using strftime on it to convert it to a string... but that didn't work either. It doesn't recognize the strftime method on the value.

Any idea on how to parse this properly and get the format I want? What am I doing wrong? (And if this clearly contains a date as well as a time, why is Python automatically considering it a time object?)

+2  A: 

Have you tried str(time)? That should give it to you in a string and then you can play around with the formatting all you like.

Alex Bliskovsky
+4  A: 

You can convert it to a time object like this:

import time
time.strptime(str(thetime), '%m/%d/%y %H:%M:%S')

And then you should be able to manipulate it to your hearts content.

HTH

Wayne Werner
Tried that... I get `AttributeError: type object 'datetime.time' has no attribute 'strptime'`
froadie
I think that the `time` in `time.strptime()` is a module and not an object.
Alex Bliskovsky
@Alex Bliskovsky - not sure I get it... how do I change the code to make it work?
froadie
Sorry, I forgot to mention which module I was referring to. Fixed
Wayne Werner
@froadie: I suspect that you are importing `datetime.time` as `time` and not `time`. The former does not have a `strptime` attribute. Changing the import to `import time` should help.Alternately you can do the following: `from datetime import datetime; datetime.strptime(str(cell.Value), '%m/%d/%y %H:%M:%S')`HTH
Manoj Govindan
Thanks for the edit! I had a `from datetime import time` that was interfering. It's working now :)
froadie