【发布时间】:2015-02-26 19:16:41
【问题描述】:
我有一个包含日期的 Excel 表格。
通过以下内容,我将它们转换为日期时间对象:
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 中进行“转换”?
【问题讨论】:
-
所以你有一个日期时间对象,你需要'%d.%m.%Y'?
datetime.now().strftime('%d.%m.%Y')
标签: python datetime import-from-excel