将timedelta hh:mm转换为秒

时间:2018-06-23 04:27:54

标签: python pandas time timedelta

我似乎在任何地方都找不到,但是我正在尝试将表示为timestamps的{​​{1}}转换为hh:mm

total seconds

如果时间戳记表示为d = ({ 'A' : ['08:00','08:10','08:12','08:26','08:29','08:31','10:10','10:25','10:29','10:31'], }) df = pd.DataFrame(data=d) ,我将使用以下内容:

hh:mm:ss

但是当我在secs = (pd.to_timedelta(df['A']).dt.total_seconds()) 上尝试此操作时,出现错误了吗?

hh:mm

当显示为ValueError: expected hh:mm:ss format

时,有没有一种简单的方法可以转换时间

3 个答案:

答案 0 :(得分:1)

只需将:00附加到字符串的末尾即可将其转换为hh:mm:ss格式。

例如:08:00可以改写为08:00:00

解决此问题的快速方法:

d['A'] = [x + ':00' for x in d['A']]

然后,您可以运行以下命令:

secs = (pd.to_timedelta(d['A']).dt.total_seconds())

答案 1 :(得分:1)

如果没有“ senconds”值或您有hh:mm,则只需在每个值中添加字符串:00即可将其设置为hh:mm:ss

d['A'] = d['A'] + ':00'

&然后将其转换为timedelta64数据类型

d['A'] = pd.to_timedelta(d['A'], unit='s')

输出

        A
0   08:00:00
1   08:10:00
2   08:12:00
3   08:26:00
4   08:29:00
5   08:31:00
6   10:10:00
7   10:25:00
8   10:29:00
9   10:31:00

答案 2 :(得分:0)

您也可以通过这种方式添加秒数:

df['A'] = pd.to_datetime(df['A']).dt.strftime('%H:%M:%S')

输出:

         A
0  08:00:00
1  08:10:00
2  08:12:00
3  08:26:00
4  08:29:00
5  08:31:00
6  10:10:00
7  10:25:00
8  10:29:00
9  10:31:00
相关问题