Home > OS >  Separate values from date datatype using Pandas
Separate values from date datatype using Pandas

Time:12-17

I wish to separate values from date datatype

Data

time                            ID  
2021-04-16T00:00:00.000-0800    AA
2021-04-23T00:00:00.000-0800    AA
2021-04-30T00:00:00.000-0800    BB

Desired

time        ID  
2021-04-16  AA
2021-04-23  AA
2021-04-30  BB

Doing

df["time"] = df["time"].str.extract(r'(\w )')

Any suggestion is appreciated

CodePudding user response:

A possible solution:

df['time'] = pd.to_datetime(df['time'])
df['time'] = df['time'].dt.date

As @Umar.H suggests -- thank you! --, one can use dt.normalize, instead of dt.date, to leave the column time as datetime64:

df['time'] = df['time'].dt.normalize() 

Output:

         time  ID
0  2021-04-16  AA
1  2021-04-23  AA
2  2021-04-30  BB

CodePudding user response:

Another approach is that, you could split the time column at the 'T' character and select the first element.

df['time'] = df['time'].str.split('T').str[0]

Output:

  time        ID
0 2021-04-16  AA
1 2021-04-23  AA
2 2021-04-30  BB
  • Related