Clayton Tosatti
Clayton Tosatti

Reputation: 196

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

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:

 start_date = '2018-07-03 16:03:00'
 data_final = '2018-07-05 00:00:00'
 duration = data_final - start_date

The result I'm looking for is '31: 57: 00 ', or 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 converting it to an XMinutesHours format with the statement:

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

But I got the error:

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

Any idea?

Upvotes: 2

Views: 13587

Answers (3)

EdCornejo
EdCornejo

Reputation: 761

You need to calculate the equivalent in hours, minutes and seconds, you could implement a function to get this value, for example:

from datetime import datetime

def get_duration(duration):
    hours = int(duration / 3600)
    minutes = int(duration % 3600 / 60)
    seconds = int((duration % 3600) % 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

format_str = '%Y-%m-%d %H:%M:%S'
start_date_str = '2018-07-03 16:03:00'
end_date_str = '2018-07-05 00:00:00'

start_date = datetime.strptime(start_date_str, format_str)
end_date = datetime.strptime(end_date_str, format_str)
duration = (end_date - start_date).total_seconds()

print(get_duration(duration))

Upvotes: 5

NAGA
NAGA

Reputation: 338

First covert the columns to datetime fields using pd.to_datetime.

lets say you have a dataframe df with the column start_time.

import pandas as pd

df['start_time'] = pd.to_datetime(df['start_time']
df['end_time'] = pd.to_datetime(df['end_time']

df['time_diff'] = (df.end_time - df.start_time) #gets the time in hours

if you want to convert it to hours use:

df['time_diff'] = df['time_diff'].dt.total_seconds()/(3600.0)

But this wont give exactly in the H:M:S format.

Upvotes: 0

Joel
Joel

Reputation: 1574

What you have is a datetime.timedelta object, which is what you get from the subtration of two datetime.datetime objects. This question has already been answered here.

On a side note, it looks like you're trying to use strptime when you really want to use strftime. strptime parses a string and turns it into a datetime.datetime object (hence the p), whereas strftime formats a datetime.datetime object as a string (hence the f).

Upvotes: 0

Related Questions