如何在 python 中将时间列值从 mm:ss 格式化为 hh:mm:ss?例如,21:34 到 00:21:34

编程入门 行业动态 更新时间:2024-10-22 09:46:02
本文介绍了如何在 python 中将时间列值从 mm:ss 格式化为 hh:mm:ss?例如,21:34 到 00:21:34的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在时间列中,有如下值:

In time column, there are values like:

Time
========
 59:47
 59:52
 59:53
 59:55
 1:00:01
 1:00:03
 1:00:12

现在,我需要重塑像 hh:mm:ss 这样的值

Now, I need to reshape the values like hh:mm:ss

我尝试过这样的事情:

time_list = df7['Time'].tolist()

for i in time_list:
    print(datetime.strptime(i,'%H:%M:%S'))

ValueError: 时间数据36:21"与格式%H:%M:%S"不匹配

ValueError: time data ' 36:21' does not match format '%H:%M:%S'

推荐答案

如果你可以将你的值标准化为 mm:sshh:mm:ss 形式code>,没有额外的组件,那么就像做这样的事情一样简单:

If you can normalise your values to always be of the form mm:ss or hh:mm:ss, with no additional components to them, then it's as simple as doing something like this:

for time_string in time_list:
    if time_string.count(':') == 1:
        time_string = '00:' + time_string
    print(datetime.strptime(time_string,'%H:%M:%S'))

让我们考虑问题中发布的示例数据:

Let's consider the sample data posted in the question:

time_list = ['59:47', '59:52', '59:53', '59:55', '1:00:01', '1:00:03', '1:00:12']

输出结果如下:

1900-01-01 00:59:47
1900-01-01 00:59:52
1900-01-01 00:59:53
1900-01-01 00:59:55
1900-01-01 01:00:01
1900-01-01 01:00:03
1900-01-01 01:00:12

不过,我认为由于这是时间数据(没有日期组件),time.strptime() 将是一个更好的候选者:只需使用 time.strptime() 而不是 datetime.strptime() 得到这样的东西:

I think, though, that since this is time data (without a date component), time.strptime() would be a much better candidate: just use time.strptime() instead of datetime.strptime() to get something like this:

time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=59, tm_sec=47, tm_wday=0, tm_yday=1, tm_isdst=-1)

希望有帮助!:)

这篇关于如何在 python 中将时间列值从 mm:ss 格式化为 hh:mm:ss?例如,21:34 到 00:21:34的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:27:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   格式   时间   如何在   ss

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!