23

I received the servertime from the Binance-API,I try to work with and it looks like this:

{
  "serverTime": 1518440400000
}

The question is, how can I compute the date out of this stamp?

I tried

import datetime

print(datetime.datetime.fromtimestamp(
       int("1518308894652")).strftime('%Y-%m-%d %H:%M:%S'))

But the date wasn´t valid.

Do you have ideas, or is it to specific? Thank you!

cosmonaut
  • 414
  • 1
  • 3
  • 14
  • 1
    Is `1518440400000` is the actual timestamp you got back? If so, that would mean the server is running in the year 50087... But assuming that's just an example, most languages should have some function for this. What language are you using? – Addison Feb 13 '18 at 01:12
  • this is the same, what I got. I use python. – cosmonaut Feb 13 '18 at 01:14
  • 2
    Question would have been so much more useful if you had posted the Binance API request. – P i Mar 13 '21 at 02:56

3 Answers3

38

You could use this:

from datetime import datetime
datetime.fromtimestamp(int("1518308894652"))

But python says the year is out of range (understandably, considering it says it's 50087). So I suspect that serverTime is not a normal timestamp.

But assuming the response that you got was the timestamp, so you don't need to do any other conversions other than turning the string into an int.

Edit:

Turns out the docs say "All time and timestamp related fields are in milliseconds." So just divide the response by 1000 and you'll be fine: datetime.fromtimestamp(int("1518308894652")/1000). Source

Addison
  • 3,791
  • 3
  • 28
  • 48
  • I tried, but receive "ValueError: year 50083 is out of range" :/ – cosmonaut Feb 13 '18 at 01:22
  • 1
    @cosmonaut I edited the question with the fix. The Binance API docs gives the time is in milliseconds, whereas python expects a value in seconds. – Addison Feb 13 '18 at 01:27
  • @AidanGawronski I don't know if you're referring to the fact that accepted answer was switched, or my answer itself. I'm super sorry that that it was switched, I didn't mean for that to happen. I wrote a short answer while I researched the problem further, planning to edit my answer to give more info on the problem, and in that time you posted your answer. But I found all of this completely independently, I just googled "Binance API". – Addison Feb 14 '18 at 03:13
  • Fair enough. I believe you. – AidanGawronski Feb 14 '18 at 14:32
18

Your response is in milliseconds when datetime.fromtimestamp requires seconds.

import datetime

print(datetime.datetime.fromtimestamp(1518308894652/1000))

# 2018-02-10 19:28:14.652000
AidanGawronski
  • 2,055
  • 1
  • 14
  • 24
3

Pandas can handle this perfectly by specifying miliseconds as the unit.

import pandas as pd
pd.to_datetime(1518440400000, unit='ms')

Timestamp('2018-02-12 13:00:00')

Alan
  • 49
  • 5