B.W.
B.W.

Reputation: 92

Removing " x days " from datetime.timedelta object

I need to create a report where I need to subtract two dates and return it in the form of %H:%M%S

This is the subtraction which I inserted into a list :

time_difference_temp=datetime.strptime(next_time,"%Y-%m-%d %H:%M:%S") - datetime.strptime(current_time,"%Y-%m-%d %H:%M:%S")
time_difference.append(time_difference_temp)
return time_difference

this list returns to >

def push_to_csv(time_difference):
    df = pd.read_csv('time_differences.csv')
    df["Delta"] = time_difference
    df.dropna(subset=["Data"], inplace=True)
    df.to_csv("Final_ReportX.csv")

in the csv Final_ReportX it saved in the form : 0 days 00:05:39

I need it to return just 00:05:39, no days.

*regex is not an option

Thanks!

Upvotes: 1

Views: 525

Answers (1)

FObersteiner
FObersteiner

Reputation: 25544

you can use a custom function that converts timedelta to H:M:S string:

def td_to_str(td):
    """
    convert a timedelta object td to a string in HH:MM:SS format.
    """
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    return f'{int(hours):02}:{int(minutes):02}:{int(seconds):02}'

s = pd.Series(pd.to_timedelta(['1 day, 00:05:39']))

s.apply(td_to_str)
# 0    24:05:39
# dtype: object

Upvotes: 1

Related Questions