将持续时间格式化为“ hh:mm:ss”,并写入pandas数据框,并将其保存为CSV文件

时间:2019-04-11 12:22:56

标签: python-3.x pandas export-to-csv timedelta

我将数据从CSV文件导入了pandas数据框。

然后,通过相差2 datetime列来创建工期列,如下所示:

df['Drive Time'] = df['Delivered Time'] - df['Pickup Time']

现在,我想将其保存回CSV文件,但是我希望在使用Excel打开时,“驱动器时间”列以“ hh:mm:ss”格式显示。我使用的代码如下:

import pandas as pd
import numpy as np

df = pd.read_csv("1554897620.csv", parse_dates = ['Pickup Time', 'Delivered Time'])

df['Drive Time'] = df['Delivered Time'] - df['Pickup Time']

df.to_csv(index=False)

df.to_csv('test.csv', index=False)

最后,我想在导出为CSV时以“ hh:mm:ss”的格式保存“行车时间”列

1 个答案:

答案 0 :(得分:0)

如果您知道Delivered Time永远不会超过24小时,则可以使用以下技巧:

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=['Delivered Time', 'Pickup Time'])
df['Delivered Time'] = pd.date_range('2019-01-01 13:00', '2019-01-02 13:00', periods=12)
df['Pickup Time'] = pd.date_range('2019-01-01 12:00', '2019-01-02 12:00', periods=12)
df['Drive Time'] = df['Delivered Time'] - df['Pickup Time']

# Trick: transform timedelta to datetime object to enable strftime:
df['Drive Time'] = pd.to_datetime(df['Drive Time']).dt.strftime("%H:%M:%S")

df.to_csv('test.csv')

通过将timedelta转换为日期时间数据类型,可以使用其strftime方法。