Convert Days & Time (Hours x Minutes x Seconds) to Time only

Asked

Viewed 899 times

2

I have a Dataframe in which I am 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', that is the total time of the difference between the two dates. But the result I have is : '1 day, 7:57:00'(Every 24 hours he writes as 1 day).

I tried to convert to a format of Horasxminutos with the instruction:

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

But I got the mistake:

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

Any idea?

  • I don’t understand the doubt, Maniero. I gave the examples, the result I got, the code I used and what I expected to receive as a response, or I was completely specific in what I was looking for. Why does the pendencia?

  • This question is very clear - I ask that it be reopened - the only thing missing is a tag "pandas" - which clears up quite , since those who look know which addition and difference functions are being used. I and other familiar people know of "pandas" because of the word "dataframe" in the body of the question - but without this tip straight in the tags it is rather awkward - since the examples shown do not happen in Python "pure".

  • Thank you very much for the jsbueno remark

1 answer

3


The problem is that the %H of the datetime.strftime goes only up to 23. As per 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 to 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'
  • Excellent Begnini worked perfectly, thank you very much! There really had been no attack on this issue of %H, good observation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.