我想用xlsxwriter寫出我的熊貓表。我有兩列:熊貓Xlsxwriter時間格式
Date | Time
10/10/2015 8:57
11/10/2015 10:23
但是當我使用xlsxwriter,輸出爲:
Date | Time
10/10/2015 0.63575435
11/10/2015 0.33256774
我嘗試使用DATETIME_FORMAT = 'HH:MM:SS',但這並沒有改變它。如何在不影響日期欄的情況下正確格式化日期?
我想用xlsxwriter寫出我的熊貓表。我有兩列:熊貓Xlsxwriter時間格式
Date | Time
10/10/2015 8:57
11/10/2015 10:23
但是當我使用xlsxwriter,輸出爲:
Date | Time
10/10/2015 0.63575435
11/10/2015 0.33256774
我嘗試使用DATETIME_FORMAT = 'HH:MM:SS',但這並沒有改變它。如何在不影響日期欄的情況下正確格式化日期?
以下代碼適用於我,但有一些注意事項。如果自定義格式化工作取決於您打開的Windows/Excel版本。優先自定義格式取決於Windows操作系統的語言設置。
所以,是的,沒有最好的解決方案......但這個想法是改變每個列的格式,而不是改變如何解釋數據類型的整個的excel文件正在創建。
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()
當我嘗試將它設置爲timedelta或datetime時('TypeError:類型'datetime.time'的對象沒有len()'),熊貓數據幀錯誤。至少我已經縮小了現在的問題 - 希望一旦我修復了熊貓表,那麼這將工作。 – Abi
「Time」列的dtype是什麼?你能發佈'df.info()'的輸出嗎? – EdChum
對於'日期'和'時間'列,它們都是非空對象。 – Abi
所以他們是'str'而不是'datetime'?如果沒有發佈我詢問的內容 – EdChum