Excel 输出中的 Python Pandas 自定义时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25898839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:28:44  来源:igfitidea点击:

Python Pandas custom time format in Excel output

pythonexcelpandasformattingmilliseconds

提问by wrcobb

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

我曾经pandas.groupby在两列上对 Pandas DataFrame 进行分组并计算平均时间和中值时间。我得到的数据集看起来类似于:

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).

我想将此表导出到 excel 并将时间列格式化为 Excel 中的自定义格式(hh:mm:ss.000)。换句话说,我想将时间视为毫秒级时间。例如,以这种方式格式化的 0.000310995 显示为 00:00:26.870(26.870 秒)。

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.638400in the DataFrame. However, when using to_excelto export to Excel they are formatted as 1970-01-01 00:02:58in the Excel output. At this point, I only need to drop the date portion and add millisecond precision to achieve my goal. Any thoughts?

我通过使用to_datetime(df['Average Time'], unit='d'). 我的时间现在像1970-01-01 00:02:57.638400在 DataFrame 中一样格式化。但是,当to_excel用于导出到 Excel 时,它们的格式1970-01-01 00:02:58与 Excel 输出中的格式相同。此时,我只需要删除日期部分并添加毫秒精度即可实现我的目标。有什么想法吗?

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

非常感谢您提供的任何帮助 -

回答by jmcnamara

You can use the datetime_formatparameter of ExcelWriterin Pandas:

您可以使用Pandas 中的datetime_format参数ExcelWriter

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:

这给出了以下输出:

enter image description here

在此处输入图片说明

See also Working with Python Pandas and XlsxWriter.

另请参阅使用 Python Pandas 和 XlsxWriter