Home > database >  How to remove leading zero's from Time column in Data frame pandas
How to remove leading zero's from Time column in Data frame pandas

Time:04-05

I have a dataframe like this:

Time       
07:20:45        
05:19:41       
10:16:26         
10:54:10

I want to remove leading zeros from the Time column:

Time       
7:20:45        
5:19:41       
10:16:26         
10:54:10

The code I'm using:

df1['Time'] = df1['Time'].apply(lambda x: x.lstrip('0'))

Error it's throwing:

AttributeError: 'datetime.time' object has no attribute 'lstrip'

CodePudding user response:

What ever the reason is to do that, in this case you could cast the pandas object to a string, so stripping will be possible:

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

CodePudding user response:

Pandas shows you a string representation of a datetime object - you have a datetime object in that column, NOT a string. There is no 0 to remove from it ....

You would need to format your datetime into a time-string, then can crop unwanted characters - may need some refining though:

import pandas as pd

t  = pd.Timestamp.now().time

df_times = pd.DataFrame()
df_times['datetime'] =  pd.date_range("00:00:00", "07:01:00", periods=6)
df_times["formatted"] = df_times['datetime'].dt.strftime('%H:%M:%S').str.lstrip("0:")


print(df_times)

Output:

            datetime formatted
0 2022-04-04 00:00:00              # all was stripped
1 2022-04-04 01:24:12   1:24:12
2 2022-04-04 02:48:24   2:48:24
3 2022-04-04 04:12:36   4:12:36
4 2022-04-04 05:36:48   5:36:48
5 2022-04-04 07:01:00   7:01:00
  • Related