f0rd42 f0rd42 - 1 year ago 151
Python Question

converting a datetime object

with the help of @JRichardSnape and others I was able to get most of the stuff sorted in my little script.
I have an excel sheet which contains date.

it the following I convert them to datetime objects:

def excel_time_to_string(xltimeinput):
retVal = xlrd.xldate.xldate_as_datetime(xltimeinput, wb.datemode)
except ValueError:
print('You passed in an argument in that can not be translated to a datetime.')
print('Will return original value and carry on')
retVal = xltimeinput
return retVal

The I define the columns which contain dates and use that def on these cells:

date_cols = [16, 18, 29, 42, 43]

headerrow = wb.sheet_by_index(0).row_values(0)

for rownum in xrange(1,wb.sheet_by_index(0).nrows):
# Get the cell values and then convert the relevant ones before writing
cell_values = wb.sheet_by_index(0).row_values(rownum)
for col in date_cols:
cell_values[col] = excel_time_to_string(cell_values[col])

so far so good, I get the correct object written in my csv:
2008-09-30 00:00:00

BUT, I need it in a different format: %d.%m.%Y

Am I right in my thinking that I have to do that "conversion" in the for loop instead of in the def? (Sorry, complete newbie on a learning path)



Answer Source

I am not familiar with xlrd, but from what I can tell, the function you use (xlrd.xldate.xldate_as_datetime) returns a python datetime.datetime object.

datetime.datetime objects have a specific format (therefore, retVal has a specific format), but you can change it using the datetime.strftime() method.

>>>import datetime
>>>x = datetime.today()
2015-02-26 11:31:31.432000

You can do this conversion directy on retVal in your function, e.g.

retVal = retVal.strftime('desired format')

Read more here: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download