简体   繁体   中英

How can I format datetime with na in python 3 pandas

I have in pandas table of dates with NAs:

0    2017-04-04 00:00:00
1    2018-09-20 00:00:00
2    na
3    2018-09-01 00:00:00
4    na
5    2018-01-01 00:00:00

I need to change table into string type without time, with format of dates separated by dots and na's replaced with empty string ''

0    04.04.2017
1    20.09.2018
2    
3    01.09.2018
4    
5    01.01.2018

if I use strftime('%d.%m.%Y') I receive error. If I use dt.date it gives me wrong format: 2017-04-04

Use strftime , but for replace NaT s use replace :

#if necessary
#df['col'] = pd.to_datetime(df['col'])
df = df['col'].dt.strftime('%d.%m.%Y').replace('NaT','')
print (df)
0    04.04.2017
1    20.09.2018
2              
3    01.09.2018
4              
5    01.01.2018
Name: col, dtype: object

You're on the right track! Just be aware that calling fillna converts the column to a non-datetime type. But you can call str.replace after converting.

df['date'].dt.date.fillna('')\
     .astype(str).str.split('-').str[::-1].str.join('.')

0    04.04.2017
1    20.09.2018
2              
3    01.09.2018
4              
5    01.01.2018
Name: date, dtype: object

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