简体   繁体   中英

Pandas: how to create two new columns in a dataframe with an existing string data column

I have a column date (string type for each row) in my dataframe that looks like this:

1      'Sat, 26 Dec 2020 14:05:59 +0000'
2      'Sat, 26 Dec 2020 11:01:27 +0000'
3      'Sat, 26 Dec 2020 12:43:59 +0000'
4      'Sat, 26 Dec 2020 13:24:45 +0000'
5      'Sat, 26 Dec 2020 13:37:00 -0000'

I would like to create two new columns like this:

Date                Hour
'Sat, 26 Dec 2020'   '14:05:59'
'Sat, 26 Dec 2020'   '11:01:27'

How can I do this? Knowing that at the beginning the type is string. I thought about cutting with the len because the format is always the same for each row at the beginning. But maybe it's not the best method.

assuming your original column name is datetime you can do the following:

df['date']=pd.to_datetime(df['datetime']).dt.strftime('%a, %d %b %Y')
df['time']=pd.to_datetime(df['datetime']).dt.strftime('%H:%M:%S')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM