0

I have epoch time like this 1488445200000 and I need to convert it to datetime variable. I tried

from datetime import datetime
dt = datetime.fromtimestamp(1488445200000 // 3600)
dt

I got

datetime.datetime(1983, 2, 7, 10, 10)

but the result does not seem to be right (the right one should be March 2, 2017 10:00:00 AM GMT+01:00)... what shall I do?

And what if what is I need to do is not just for one value 1488445200000 but for a column in a dataframe. Do I have to loop? Or is there a matrix operation?

2 Answers2

2

Your timestamp is in milliseconds and datetime expects seconds. Divide by 1000 and it works:

$ python3 
Python 3.7.0 (default, Jun 29 2018, 20:13:13) 
[Clang 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(1488445200000 // 1000)
>>> dt
datetime.datetime(2017, 3, 2, 10, 0)
olehermanse
  • 336
  • 1
  • 7
  • Great! Thanks. Just one more question. What is I need to do this for a column in a dataframe. Do I have to loop? Or is there a matrix operation? –  Nov 06 '18 at 12:58
  • I don't know anything about dataframes. Looping is probably the easiest, but you may also be able to apply the fromtimestamp function using something like: https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.agg.html#pandas.DataFrame.agg – olehermanse Nov 06 '18 at 13:35
  • @MattJohnson I didn't? – olehermanse Nov 06 '18 at 18:33
  • @MattJohnson Ah, makes sense. No problem :) – olehermanse Nov 06 '18 at 18:36
0

Try This:

Use datetime module:

from datetime import datetime
ts = int(1488445200000//1000)
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
Rohit-Pandey
  • 2,039
  • 17
  • 24