2

I am trying to transition my reports that are currently automated with VBA to python. But since i work with lots of durations on my exports I have a problem.

If i want to do some measures with this data that is in "%H:%M:%S" format I have to convert it using:

df['Duration'] = pd.to_timedelta(df['Duration'])

But when I save my dataframe back to csv it saves the data as 0 days 00:09:17.000000000 and I need it to be saved with the format %H:%M:%S.

Am I doing it wrong? Thanks

Karvu
  • 23
  • 3
  • You could create a column that has the string representation you want before you save. If you are opening it in Excel, maybe you can format the column in Excel. – Vincent Feb 28 '21 at 05:46
  • If the duration can be more than 24 hours, there will be a 'n days' prefix if converted to string. See [this post](https://stackoverflow.com/a/8907269/15070697) for a customized formatting. – SeaBean Feb 28 '21 at 06:14
  • if you want a specific format for `timedelta`, write your own function that formats to string. [Example](https://stackoverflow.com/a/66278958/10197418). – FObersteiner Feb 28 '21 at 16:31

1 Answers1

1

Time Delta is difference between 2 dates/time so that's why it saves data as

0 days 00:09:17.000000000

If you want to save data as 00:09:17.000000000 then After you run

df['Duration'] = pd.to_timedelta(df['Duration']) 

then convert its dtype to string by:-

df['Duration'] = df['Duration'].astype('str')

and finally:-

df['Duration']=df['Duration'].apply(lambda x:x.split(' ')[2])

Note:- it store data as object type not timedelta type

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41