Brenda Xavier
Brenda Xavier

Reputation: 129

Change of value to the converter Int64 in string Python

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 ?

Upvotes: 0

Views: 695

Answers (2)

Brenda Xavier
Brenda Xavier

Reputation: 129

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'))

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

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

Upvotes: 0

Related Questions