0

I have a problem understanding what causes the date value to change when I convert.

I have the following value "19670619", type int64. I need to convert to String and leave the date "06/19/1967".

I did it this way:

Op['dt'] = pd.to_datetime(Op['dt'], unit = 'ms')
Op['dt'] = Op['dt'].fillna(datetime(2200,12,31))
OP['dt'] = Op['dt'].apply(lambda x: x.strftime('%d/%m/%Y'))

I have the result: 01/01/1970 which is different from the original date it entered. Another way I tried was:

Op['dt'] = pd.to_datetime(Op['dt'], unit = 'm')
Op['dt'] = Op['dt'].fillna(datetime(2200,12,31))
OP['dt'] = Op['dt'].apply(lambda x: x.strftime('%d/%m/%Y'))

And the result was: 27/05/2007, I can not understand why this happened even when reading the other conversion cases. Can anybody help me ?

rafaelc
  • 57,686
  • 15
  • 58
  • 82

2 Answers2

1

I solved my problem as follows.

Op['dt'] = pd.to_datetime(Op['dt'], format='%Y%m%d')
Op['dt'] = pd.to_datetime(Op['dt'], unit = 's')
Op['dt'] = Op['dt'].fillna(datetime(2200,12,31))
Op['dt'] = Op['dt'].apply(lambda x: x.strftime('%d/%m/%Y'))
0

Try pd.to_datetime(df["dt"]).dt.strftime('%d/%m/%Y')

Ex:

import pandas as pd
df = pd.DataFrame({"dt" : [ "19670619"]})
df["dt"] = pd.to_datetime(df["dt"]).dt.strftime('%d/%m/%Y')
print(df)

Output:

           dt
0  19/06/1967
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Fui aplicar dessa forma e me retorno o erro "can only use .dt accessor with datetimelike values". Vi em uma pergunta para colocar "coerce=True", fiz isso e deu certo para aplicar na coluna "dt", porém o resultado das datas continuam alteradas, não estão com o valor que deveria retornar – Brenda Xavier Jun 13 '18 at 13:50