简体   繁体   中英

Converting dtype('O') to a date DD/MM/YYYY

im a begginer at coding and started a project for my small business.

i imported a xlsx file using panda and got the table with dtype('O') at every columns

me sheet

but i can't find anywhere a way to get only the date in the format DD/MM/YYYY

any tips?

i have tried this code

tabela['dt_nasc'] = pd.to_datetime(tabela['dt_nasc'], format='%m/%d/%Y')

but the results were

ValueError: time data '1988-10-24 00:00:00' does not match format '%m/%d/%Y' (match)

i also tried another code

import datetime
def convert_to_date(x):
    return datetime.datetime.strptime(x , '%Y-%m-%d %H:%M:%S')
    
    tabela.loc[:, 'dt_nasc'] = tabela['dt_nasc'].apply(convert_to_date)
    
    # better to use a lambda function
    tabela.loc[:, 'dt_nasc'] = tabela['dt_nasc'].apply(lambda x:datetime.datetime.strptime(x , '%Y-%m-%d %H:%M:%S'))

but couldn't find a way to print at format DD/MM/YYYY

Example

s = pd.Series({0: '2022-11-29 13:00:00', 1: '2022-11-30 13:48:00'})

s

0    2022-11-29 13:00:00
1    2022-11-30 13:48:00
dtype: object <-- chk dtype

Code

object to datetime

pd.to_datetime(s)

result

0   2022-11-29 13:00:00
1   2022-11-30 13:48:00
dtype: datetime64[ns] <--chk dtype

convert result to DD-MM-YYYY HH-mm-ss

pd.to_datetime(s).dt.strftime('%d-%m-%Y %H:%M:%S')

0    16-11-2022 13:00:00
1    17-11-2022 13:48:00
dtype: object <--chk dtype

convert result to DD/MM/YYYY

pd.to_datetime(s).dt.strftime('%d/%m/%Y')

0    29/11/2022
1    30/11/2022
dtype: object <-- chk dtype

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