转换日期时间对象

converting a datetime object

我有一个包含日期的 excel sheet。

通过以下我将它们转换为日期时间对象:

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

我定义了包含日期的列并在这些单元格上使用该定义:

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)

到目前为止一切顺利,我在我的 csv 中写入了正确的对象: 2008-09-30 00:00:00

但是,我需要不同格式的它:%d.%m.%Y

我认为必须在 for 循环而不是在 def 中执行 "conversion" 的想法是否正确?

我不熟悉 xlrd,但据我所知,你使用的函数 (xlrd.xldate.xldate_as_datetime) returns 一个 python datetime.datetime 对象。

datetime.datetime 对象具有特定格式(因此,retVal 具有特定格式),但您可以使用 datetime.strftime() 方法更改它。

>>>import datetime
>>>x = datetime.today()
>>>print(x)
2015-02-26 11:31:31.432000
>>>x.strftime('%d.%m.%Y')
'26.02.2015'

您可以在您的函数中直接对 retVal 执行此转换,例如

retVal = retVal.strftime('desired format')

在此处阅读更多内容: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior