I am absolute beginner in python, so the solution must be trivial, but I just cannot figure it out. I have dates in format 19690101 (yyyymmdd) in a DF that I want to convert to dates. to_datetime does the job, except that it gives a wrong date 1970-01-01 00:00:00.019690101. How can I fix this? Thanks. here is my bit of code
CodePudding user response:
You need to declare the format the date is in before you convert it to the desired format.
from datetime import datetime
wrong_date = "19690101"
date = datetime.strptime(wrong_date,"%Y%m%d").strftime("%d/%m/%Y")
print (date)
CodePudding user response:
because your date is a number. convert it to a string first.
pd.to_datetime(str(19690101), format='%Y%m%d')
or
pd.to_datetime(df.birthdate.astype(str), format='%Y%m%d')