Remove both Leading and Trailing zeros from Date

Question:

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

    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

Asked By: NoobLearner

||

Answers:

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
Answered By: Bhargav

Use str.strip:

df['time_col'] = df['time_col'].str.strip('0')

NB. There are also str.lstrip and str.rstrip to limit to left/right stripping respectively.

Output:

   time_col
0   2:10:41
1   9:19:22
2  10:55:46
3   30:64:5
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.