首页 > 解决方案 > 需要将时间转换为 h:m:s

问题描述

我的时间格式缺少 36:21 或不完整的小时格式,如 1:23:30,想将其转换为标准时间格式,如 00:00:00,但我不知道为什么我的代码不起作用.

需要像这样转换时间格式 H:M:S --> 00:00:00 len(x) == 6 即 36:21 ; len(x) == 7 即 1:23:30

想得到 00:36:21 和 01:23:30

for x in df7[' Chip Time']:
    if len(x) == 6: 
        x = '00:'+ x
    elif len(x) == 7:
        x = '0'+ x
    print (df7[' Chip Time']) 

==================================================== ========= 需要支持。谢谢!

标签: pythonpandas

解决方案


你应该使用 apply 方法,它比迭代快得多

我还建议您阅读https://thispointer.com/python-how-to-pad-strings-with-zero-space-or-some-other-character/

这应该工作:

df7[' Chip Time'] = df7[' Chip Time'].apply(lambda x : x.rjust(5, '0').rjust(6, ':').rjust(8, '0'))


推荐阅读