简体   繁体   中英

python pandas: split string into date and time in datetime format

I have a field in my dataframe df, labeled date, but after testing it a lot, I figured out that it is a string and not a date format.

Transaction_id | Date
ABC              4/1/2016 9:13:58 PM
CDE              10/3/2015 10:12:25 AM
EFG              12/12/2017 3:02:45 PM

I need to split the Date column up into Date & time and I want them to be in datetime format. I don't know how to do this with regex, since the lengths are different.

Output:

Transaction_id | Date                    | Date2       | Time            
ABC              4/1/2016 9:13:58 PM       04/01/2016    21:13:58
CDE              10/3/2015 10:12:25 AM     10/03/2016    10:12:25
EFG              12/12/2017 3:02:45 PM     12/12/2017    15:02:45

Note that I placed a errors='coerce' to handle non-sensical date data.

date2 = pd.to_datetime(df.Date, errors='coerce')

df.assign(Date2=date2.dt.date, Time=date2.dt.time)

  Transaction_id                   Date       Date2      Time
0            ABC    4/1/2016 9:13:58 PM  2016-04-01  21:13:58
1            CDE  10/3/2015 10:12:25 AM  2015-10-03  10:12:25
2            EFG  12/12/2017 3:02:45 PM  2017-12-12  15:02:45

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