简体   繁体   中英

How to convert epoch time to time

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?

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)

Try This:

Use datetime module:

from datetime import datetime
ts = int(1488445200000//1000)
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM