I used
pd.to_numeric (df['dates'], downcast = 'integer')
to convert a datetime64 to int64 but if I want to convert it back to datetime format, what should I do?
Earlier it was in format: 2020-02-19 but after conversion it is now 1582070400000000000. I can't find a way to revert it back to datetime64.
1 Answer
Pandas to_datatime does the trick
See example:
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'dates' : pd.date_range('01-01-2021','01-10-2021',freq='D')})
# To numeric, as you did
df['numeric'] = pd.to_numeric (df['dates'] , downcast = 'integer')
# Back to date
df['back_do_date'] = pd.to_datetime( df['numeric'] )
gives the DataFrame: df
dates numeric back_do_date
0 2021-01-01 1609459200000000000 2021-01-01
1 2021-01-02 1609545600000000000 2021-01-02
2 2021-01-03 1609632000000000000 2021-01-03
3 2021-01-04 1609718400000000000 2021-01-04
4 2021-01-05 1609804800000000000 2021-01-05
5 2021-01-06 1609891200000000000 2021-01-06
6 2021-01-07 1609977600000000000 2021-01-07
7 2021-01-08 1610064000000000000 2021-01-08
8 2021-01-09 1610150400000000000 2021-01-09
9 2021-01-10 1610236800000000000 2021-01-10
pd.to_datetime(df['dates'])?pd.to_datetime(1582070400000000000)?pd.to_datetimeworks for me,pd.Timestamp(1582070400000000000)also works.