问题描述
限时送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:ss
或 hh: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:关键词]
发布评论