datetime - Convert class 'pandas.tslib.Timedelta' to string when export to excel -


initial dataframe:

arrivaltime         0   2016-01-12 06:35:42 2   2016-01-12 06:54:02 3   2016-01-12 07:01:43 4   2016-01-12 07:02:28 5   2016-01-12 07:12:29 6   2016-01-12 07:18:41  

on data apply function:

def function(df):     df['arrivaltime_cal'] = pd.to_datetime(df['arrivaltime'], format='%y-%m-%d %h:%m:%s')     df['diff_time'] = df['arrivaltime_cal'].diff().fillna(0)     del df['arrivaltime_cal']     return df 

and these results (corrects in ipython):

diff_time   0  00:00:00   1  00:04:37   2  00:13:43   3  00:07:41   4  00:00:45 

when export excel result change format:

arrivaltime             diff_time 0   2016-01-12 06:35:42 0 1   2016-01-12 06:40:19 0,003206019 2   2016-01-12 06:54:02 0,009525463 3   2016-01-12 07:01:43 0,005335648 4   2016-01-12 07:02:28 0,000520833 

how keep string format in excel?

thank in advance

iiuc can cast type str , split str:

in [53]: df['diff_time'].astype(str).str.split().str[-1].str.rsplit('.').str[0]  out[53]: index 0    00:00:00 2    00:18:20 3    00:07:41 4    00:00:45 5    00:10:01 6    00:06:12 dtype: object 

breaking above down steps, cast str using astype:

in [54]: df['diff_time'].astype(str)  out[54]: index 0    0 days 00:00:00.000000000 2    0 days 00:18:20.000000000 3    0 days 00:07:41.000000000 4    0 days 00:00:45.000000000 5    0 days 00:10:01.000000000 6    0 days 00:06:12.000000000 name: diff_time, dtype: object 

now split (default character spaces) , take last split element time component:

in [55]: df['diff_time'].astype(str).str.split().str[-1]  out[55]: index 0    00:00:00.000000000 2    00:18:20.000000000 3    00:07:41.000000000 4    00:00:45.000000000 5    00:10:01.000000000 6    00:06:12.000000000 dtype: object 

now rsplit , take time minus hte microseconds

in [56]: df['diff_time'].astype(str).str.split().str[-1].str.rsplit('.')  out[56]: index 0    [00:00:00, 000000000] 2    [00:18:20, 000000000] 3    [00:07:41, 000000000] 4    [00:00:45, 000000000] 5    [00:10:01, 000000000] 6    [00:06:12, 000000000] dtype: object 

you can see converted values indeed str:

in [57]: df['diff_time'].astype(str).str.split().str[-1].str.rsplit('.').str[0][0]  out[57]: '00:00:00' 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -