Python Pandas: Dataframe convert Timestamp column to Datetime

Asked

Viewed 433 times

2

How can I convert a Dataframe column from Timestamp to Datetime?

btc_df = pd.DataFrame ( bars_day , columns=['date' , 'volume' , 'open' , 'high' , 'low' , 'close'] )

Summary

date       int64
volume    object
open      object
high      object
low       object
close     object
dtype: object
                 volume      open  ...
date                               ...                          
1610323200000  38150.02  38264.74  ...
1610409600000  35410.37  36628.00  ...
1610496000000  34049.15  37850.00  ...
1610582400000  37371.38  40100.00  ...
1610668800000  39145.21  39747.76  ...

Thank you!

1 answer

1


import pandas as pd

data = [1610323200000,1610409600000,1610409600000,1610496000000,1610582400000]
volume = [38150.02,35410.37,34049.15,37371.38,39145.21]
abertura = [38264.74,36628.00,37850.00,40100.00,39747.76]

You can use astype and pass datetime as parameter

df['Date'] = df['Date'].astype('datetime64[ms]')

Exit

          Date    Volume        Open
0   2021-01-11  38150.02    38264.74
1   2021-01-12  35410.37    36628.00
2   2021-01-12  34049.15    37850.00
3   2021-01-13  37371.38    40100.00
4   2021-01-14  39145.21    39747.76
  • Thanks for the reply however how can I get the date + time? Any recommendations?

  • @LEANDROFIGUEIRA, good afternoon! You can use the pd.to_datetime(df['Date']). Hug!

  • This I’m not getting: '' btc_df['date'] = btc_df['date']. astype('datetime64[ns]') 1970-01-01 00:26:50.323200 btc_df['date'] = btc_df['date']. astype('datetime64[ms]') 2021-01-11 btc_df['date'] = pd.to_datetime(btc_df['date']) 1970-01-01 00:26:50.323200 '' You cannot return in the same date+time object?

  • @LEANDROFIGUEIRA Its time is a set of zeros, so the pandas 'eliminates' the hour. If you put for example 1 in the last number it will return you the date and time (do a test). With the dates you have there you have to treat them as ms, as we would need to have more numbers on your timestamp. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.