Home > database >  How to convert the following time string of days to hours?
How to convert the following time string of days to hours?

Time:01-24

x1 , y1 , 3 days 05:30:06.96 , 3 days 06:00:01.96
x2 , y2 , 3 days 05:30:06.96 , 3 days 06:31:16.96

I want to convert the above csv to

x1 , y1 , 77:30:06.96 , 78:00:01.96
x2 , y2 , 77:30:06.96 , 78:31:16.96

essentially convert "3 days" to 72 hours and add it to hours column (72 5)

what is a nifty way of achieving this either in python or using unix utilities?

Doesn't look like python datetime.strptime() has an option to pattern match the "3 days" part.

CodePudding user response:

Well, if there are no utilities that conform to this pattern, you can easily make do it yourself. I doubt that you can find a nice, nifty one-liner to do this very easily without some deep research, and even then you may not come across it. Assuming that there are three columns, separated by commas, you can use the split method of the string to separate it into a list of four. Then you can use split again with a space delimiter to access the third and fourth column components and do the math yourself.

def calc_time(time_str):
    ''' time_str in the format of: # days #:#:#.# '''
    data = time_str.split()
    # column 3 (index 2) should contain the : separated time
    time_data = data[2].split(':')

    # Multiplying days by 24 hours and adding extra hours
    total_hour = int(data[0]) * 24   int(time_data[0])
    
    time_data[0] = str(total_hour)

    # time_data is the : separated time, which now contains the hours   days
    return ':'.join(time_data)

line = 'x1 , y1 , 3 days 05:30:06.96 , 3 days 06:00:01.96'
data = line.split(',')
# data should be a list of 4 strings now
data[2] = ' '   calc_time(data[2])
data[3] = ' '   calc_time(data[3])

result = ','.join(data)

CodePudding user response:

This might work for you (GNU sed):

sed -E 's/ (\S ) days (..)/ $((\1*24 \2))/g;s/.*/echo "&"/e' file

Replace days and hours by a bash computation and use echo to evaluate the result.

  • Related