Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove both Leading and Trailing zeros from Date

I’ve a df Like this

   time_col

0   02:10:41
1   09:19:22
2   10:55:46
3   30:64:50

I want to remove both trailing and ‘Leading` zeros.

My expected output should look like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    time_col      Time
0   02:10:41   2:10:41
1   09:19:22   9:19:22
2   10:55:46  10:55:46
3   30:64:50   30:64:5

Any suggestions would be appriciated

>Solution :

If you want to remove Leading zeros use lstrip()

df['Time'] = df['time_col'].astype('str').apply(lambda x: x.lstrip('0'))

#output

    time_col       Time
0   02:10:41    2:10:41
1   09:19:22    9:19:22
2   10:55:46   10:55:46
3   30:64:50   30:64:50

If you want to remove Trailing zeros use rstrip()

df['Time'] = df['time_col'].astype('str').apply(lambda x: x.rstrip('0'))

#output

0   02:10:41  02:10:41
1   09:19:22  09:19:22
2   10:55:46  10:55:46
3   30:64:50   30:64:5

Your case…If you want to remove both Leading and trailing use strip()

df['Time'] = df['time_col'].astype('str').apply(lambda x: x.strip('0'))

#output

    time_col      Time
0   02:10:41   2:10:41
1   09:19:22   9:19:22
2   10:55:46  10:55:46
3   30:64:50   30:64:5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading