0

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.

3
  • pd.to_datetime(df['dates'])? Commented Jun 25, 2021 at 10:29
  • 1
    And you didn't consider reading up on documentation how to convert to a datetime in Pandas ( pandas.pydata.org/docs/reference/api/… ). Say, pd.to_datetime(1582070400000000000)? Commented Jun 25, 2021 at 10:29
  • pd.to_datetime works for me, pd.Timestamp(1582070400000000000) also works. Commented Jun 25, 2021 at 10:31

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.