简体   繁体   中英

How to modify date format column in pandas dataframe to a int using python

Have a df with columns name and exm_date

name          exm_date                             
tom       2019-03-05 11:48:03.166              
mark      2018-03-05 11:48:03.166                   
matt      2020-08-05 11:48:03.166                
rob       2020-06-05 11:48:03.166              
chuck     2020-02-05 11:48:03.166               
tom       2020-03-05 11:48:03.166              
matt      2020-02-05 11:48:03.166                 
chuck     2020-06-05 11:48:03.166                    

how to convert the date format in exm_date into a format removing the time stamp and exluding the -

expected_output

name          exm_date                         code_date    
tom       2019-03-05 11:48:03.166              20190305
mark      2018-03-05 11:48:03.166              20180305     
matt      2020-08-05 11:48:03.166              20200805  
rob       2020-06-05 11:48:03.166              20200605
chuck     2020-02-05 11:48:03.166              20200205 
tom       2020-03-05 11:48:03.166              20200305
matt      2020-02-05 11:48:03.166              20200305    
chuck     2020-06-05 11:48:03.166              20200305       

Please try following code:

df['code_date'] = df['exm_date'].apply(lambda x: x.strftime("%Y%d%m"))

You can try this:

import pandas as pd
df['code_date'] = pd.to_datetime(df['exm_date']).dt.strftime('%Y%m%d')

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