How can I format time columns value from mm:ss to hh:mm:ss in python? e.g., 21:34 to 00:21:34

99封情书 提交于 2020-05-30 11:25:40

问题


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

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

I have tried something like this:

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

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

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


回答1:


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']

Here's what the output of this will look like:

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

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)

Hope that helps! :)



来源:https://stackoverflow.com/questions/57760941/how-can-i-format-time-columns-value-from-mmss-to-hhmmss-in-python-e-g-213

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!