我试图将时间从数据框写入Excel的日期中删除,但一直没有成功。
奇怪的是,我可以通过使用下面的lambda和striptime函数来操作数据框,并且可以看到函数正在由我的print df6
工作。
但是,出于某种原因,当我打开Excel文件时,它以%m%d%y: 12:00am
格式显示。我想要有日期显示。想法?
这是我的代码:
df6 = df
workbook = writer.book
df6.to_excel(writer, sheet_name= 'Frogs', startrow= 4, index=False)
df6['ASOFDATE'] = df6['ASOFDATE'].apply(lambda x:x.date().strftime('%d%m%y'))
worksheet = writer.sheets['Frogs']
format5 = workbook.add_format({'num_format': '0.00%'})
#format6= workbook.add_format({'num_format': 'mmm d yyyy'})
#worksheet.set_column('A:A', 18, format6)
worksheet.set_column('B:B', 18, format5)
worksheet.set_column('C:C', 18, format5)
worksheet.set_column('D:D', 18, format5)
now = datetime.now()
date= dt.datetime.today().strftime("%m/%d/%Y")
link_format = workbook.add_format({'color': 'black', 'bold': 1})
nrows = df6.shape[0]
worksheet.write(0, 0, 'Chart4', link_format)
worksheet.write(1, 0, 'Frogs',link_format)
#Multiply dataframe by 100 to get out of decimals (this method is used when dates are in the picture)
df6[df6.columns[np.all(df6.gt(0) & df6.lt(1),axis=0)]] *= 100
print df6
writer.save()
答案 0 :(得分:1)
strftime正在创建日期时间值的文本表示形式,稍后将根据格式化模板由Excel格式化和显示该日期时间值。我们可以使用ExcelWriter构造函数中的date_format
参数更改此格式设置模板,例如:writer = pandas.ExcelWriter("test.xlsx", engine="xlsxwriter", date_format="ddmmyyyy")
}。我稍微修改了你的样本:
import pandas as pd
import datetime
df = pd.DataFrame()
df['ASOFDATE'] = [datetime.datetime.now() for x in xrange(3)]
for i in xrange(3):
df[i] = [1,2,3]
df6 = df
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter', date_format="ddmmyyyy")
workbook = writer.book
df6.to_excel(writer, sheet_name= 'Frogs', startrow= 4, index=False)
worksheet = writer.sheets['Frogs']
format5 = workbook.add_format({'num_format': '0.00%'})
worksheet.set_column('B:B', 18, format5)
worksheet.set_column('C:C', 18, format5)
worksheet.set_column('D:D', 18, format5)
link_format = workbook.add_format({'color': 'black', 'bold': 1})
worksheet.write(0, 0, 'Chart4', link_format)
worksheet.write(1, 0, 'Frogs',link_format)
writer.save()
此代码生成一个文件,其日期值根据指定的模板格式化。