Reputation: 337
I am trying to write out my pandas table using xlsxwriter. I have two columns:
Date | Time
10/10/2015 8:57
11/10/2015 10:23
But when I use xlsxwriter, the output is:
Date | Time
10/10/2015 0.63575435
11/10/2015 0.33256774
I tried using datetime_format = 'hh:mm:ss' but this didn't change it. How else can I get the date to format correctly without effecting the date column?
Upvotes: 4
Views: 4196
Reputation: 701
The following code works for me, but there are some caveats. If the custom formatting will work depends on the Windows/Excel version you open it with. Excels custom formatting depends on the language settings of the Windows OS.
So yeah, not the best solution... but the idea is to change the formatting for each column instead of changing how to interpret a type of data for the whole excel file that is being created.
import pandas as pd
from datetime import datetime, date
# Create a Pandas dataframe from some datetime data.
df = pd.DataFrame({'Date and time': [date(2015, 1, 1),
date(2015, 1, 2),
date(2015, 1, 3),
date(2015, 1, 4),
date(2015, 1, 5)],
'Time only': ["11:30:55",
"1:20:33",
"11:10:00",
"16:45:35",
"12:10:15"],
})
df['Time only'] = df['Time only'].apply(pd.to_timedelta)
#df['Date and time'] = df['Date and time'].apply(pd.to_datetime)
# Create a Pandas Excel writer using XlsxWriter as the engine.
# Also set the default datetime and date formats.
writer = pd.ExcelWriter("pandas_datetime.xlsx",
engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects in order to set the column
# widths, to make the dates clearer.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
#PLAY AROUND WITH THE NUM_FORMAT, IT DEPENDS ON YOUR WINDOWS AND EXCEL DATE/TIME SETTINGS WHAT WILL WORK
# Add some cell formats.
format1 = workbook.add_format({'num_format': 'd-mmm-yy'})
format2 = workbook.add_format({'num_format': "h:mm:ss"})
# Set the format
worksheet.set_column('B:B', None, format1)
worksheet.set_column('C:C', None, format2)
worksheet.set_column('B:C', 20)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Upvotes: 1