Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a column of timestamps to datetime? [duplicate]

I have a dataframe with a column of dates expressed as timestamps (like [1554334020000, 1554334200000, 1554334380000, 1554334560000, 1554334740000]). How do I convert it into datetime?

I know that for a single value you can do

datetime(1970, 1, 1) + timedelta(milliseconds=int(data['Date'].values[0]))

but how do I apply that to the whole column?

like image 768
Raksha Avatar asked Dec 22 '22 23:12

Raksha


1 Answers

Use pandas.to_datetime passing argument unit='ms'

df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')

Example

df = pd.DataFrame({'timestamp': [1554334020000, 1554334200000, 1554334380000,
                                 1554334560000, 1554334740000]})
print(df)

[out]

       timestamp
0  1554334020000
1  1554334200000
2  1554334380000
3  1554334560000
4  1554334740000

df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
print(df)

[out]

            timestamp
0 2019-04-03 23:27:00
1 2019-04-03 23:30:00
2 2019-04-03 23:33:00
3 2019-04-03 23:36:00
4 2019-04-03 23:39:00
like image 107
Chris Adams Avatar answered Jan 05 '23 18:01

Chris Adams