Convert Days and Time (Hours x Minutes x Seconds) to Time Only

2

I have a Dataframe where I'm making the difference between two different dates to get the difference in Hours and Minutes, for example:

 data_inicial = '2018-07-03 16:03:00'
 data_final   = '2018-07-05 00:00:00'
 duracao      = data_final - data_inicial

The result I'm looking for is: '31: 57: 00 ', meaning the total time difference between the two dates. But the result I have is: '1 day, 7:57:00' (Every 24 hours it writes as 1 day).

I tried to convert to an XMinutes format with the statement:

print(datetime.datetime.strptime(duracao, "%H:%M:%S"))

But I got the error:

  

ValueError: time data '1 day, 7:57:00' does not match format '% H:% M:% S'

Any ideas?

    
asked by anonymous 05.07.2018 / 18:53

1 answer

2

The problem is that% H of datetime.strftime goes only to 23. According to the documentation:

  

% H-Hour (24-hour clock) as a zero-padded decimal number.

What you have to do is a function that formats this way for you. For example:

def formatehours(interval):
    seconds  = interval.total_seconds()

    # formata minutos e segundos
    duration  = datetime.datetime.utcfromtimestamp(seconds)
    formatted = duration.strftime('%M:%S')

    # formata horas e concatena com os minutos e segundos formatados
    return '%02d:%s' % (seconds / (60 * 60), formatted)

And to use just pass a timedelta for this function:

data_inicial = datetime.datetime.strptime('2018-07-03 16:03:00', '%Y-%m-%d %H:%M:%S')
data_final   = datetime.datetime.strptime('2018-07-05 00:00:00', '%Y-%m-%d %H:%M:%S')
duracao      = data_final - data_inicial

formatehours(duracao)
> '31:57:00'
    
10.07.2018 / 01:58