简体   繁体   中英

Making time format same by converting mm:ss to hh:mm:ss by adding 00 in front of mm:ss - Pandas

I have Time data, some are in format of mm:ss and some are in format of hh:mm:ss, how can I convert the data, so that every data is consistent

This is how my data of Chip Time is '59:47', '59:52', '59:53', '59:55', '1:00:01'. But when I try to implement this:

 time_list = df7['Chip Time'].tolist()
 time_mins = []
    for i in time_list:
        h,m,s = i.split(':')
        math = (int(h) * 3600 + int(m) * 60 + int(s)) / 60
        time_mins.append(math)

The error " ValueError: not enough values to unpack (expected 3, got 2) " is shown as the time 36:35 only regards as minutes and seconds as it is not in the format of 00:36:35

The same code works perfectly fine when the time in Time Chip is in the format of 00:36:45 as it splits and stores as h=00, m=36 and s= 45 but due to inconsistent pattern the error in arising.

You need to add string on condition then convert string to datetime.

import pandas as pd
from io import StringIO

data = StringIO("""
40:40
1:02:02
""")

df = pd.read_csv(data, engine='python', names=['time'])
# add string on condition
df.loc[df['time'].str.len() < 6, 'time'] = '0:' + df['time']
# convert to datetime
df['time']= pd.to_datetime(df['time'])

                 time
0 2020-09-11 00:40:40
1 2020-09-11 01:02:02

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM