Python Pandas custom time format in Excel output

ぐ巨炮叔叔 提交于 2019-12-05 02:31:47

问题


I have used pandas.groupby to group a pandas DataFrame on two columns and calculate average and median times. My resulting dataset looks similar to this:

Size        Category        Average Time        Median Time
 1             A            0.002056385         0.000310995
               B                                0.000310995
               C            0.000310995
 10            A                                0.001852681
               B            0.000310995
               C            0.000310995

I would like to export this table to excel and format the Time Columns as a custom format in Excel like so (hh:mm:ss.000). In other words, I want to view the times as millisecond-level times. For example, 0.000310995 formatted in this fashion displays as 00:00:26.870 (26.870 seconds).

Does anyone have any insight on how to accomplish this feat?

UPDATE:

I have gotten a bit closer by using to_datetime(df['Average Time'], unit='d'). My times are now formatted like 1970-01-01 00:02:57.638400 in the DataFrame. However, when using to_excel to export to Excel they are formatted as 1970-01-01 00:02:58 in the Excel output. At this point, I only need to drop the date portion and add millisecond precision to achieve my goal. Any thoughts?

Thanks very much in advance for any help you can offer -


回答1:


You can use the datetime_format parameter of ExcelWriter in Pandas:

import pandas as pd
from datetime import datetime


df = pd.DataFrame([datetime(2014, 9, 18, 12, 30, 5, 60000)])

writer = pd.ExcelWriter("time.xlsx",  datetime_format='hh:mm:ss.000')

df.to_excel(writer, "Sheet1")

writer.close()

Which gives the following output:

See also Working with Python Pandas and XlsxWriter.



来源:https://stackoverflow.com/questions/25898839/python-pandas-custom-time-format-in-excel-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!