Search code examples
pythondatetimeimport-from-excel

converting a datetime object


I have an excel sheet which contains date.

With the following I convert them to datetime objects:

def excel_time_to_string(xltimeinput):
        try:
            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

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)
    wr.writerow(headerrow)

    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])
        wr.writerow(cell_values)

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?


Solution

  • 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()
    >>>print(x)
    2015-02-26 11:31:31.432000
    >>>x.strftime('%d.%m.%Y')
    '26.02.2015'
    

    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