0

I am trying to convert a unix timestamp into a date like DD/MM/YYYY HH:MM:SS. For some reason I can not make it to work. Can you please have a look what I am doing wrong, I just started with Python 3.8.8

import requests, json
import datetime as dt
r = requests.get('https://api1.binance.com/api/v3/ticker/24hr')
jm = json.loads(r.text)
for n in range(len(jm)):
        
        x=(jm[n] ['closeTime'])
        # printing unix timestamp
        print (x)
        # trying to get the date time
        time_val = dt.datetime.fromtimestamp(x)         
        print(time_val)

Appreciate your time and help. thx.

Paul tje
  • 3
  • 1
  • Can you add example of few outputs of # printing unix timestamp i.e. what does `print (x)` output? – Daweo Sep 06 '21 at 12:49

3 Answers3

1

The timestamp you are getting is in milliseconds, you need to convert it to seconds like

time_val = dt.datetime.fromtimestamp(x/1000)  
Epsi95
  • 8,832
  • 1
  • 16
  • 34
1

That's because the API is giving the result in milliseconds, please try:

time_val = dt.datetime.fromtimestamp(x/1000.0)
farbiondriven
  • 2,450
  • 2
  • 15
  • 31
1

You should try this:

import requests, json
import datetime as dt
r = requests.get('https://api1.binance.com/api/v3/ticker/24hr')
jm = json.loads(r.text)
for n in range(len(jm)):
        
        x=(jm[n] ['closeTime'])
        # printing unix timestamp
        print (x)
        # trying to get the date time
        time_val = dt.datetime.fromtimestamp(x/1000).strftime('%Y-%m-%d %H:%M:%S')
        print(time_val)

Last Few Output:

1630932847657
2021-09-06 18:54:07
1630932864523
2021-09-06 18:54:24
1630932804755
2021-09-06 18:53:24
1630932871298
2021-09-06 18:54:31
1630932771147
2021-09-06 18:52:51
1630932862321
2021-09-06 18:54:22
1630932863872
2021-09-06 18:54:23
1630932871522
2021-09-06 18:54:31
1630932870246
2021-09-06 18:54:30
1630932872709
2021-09-06 18:54:32
1630932872684
2021-09-06 18:54:32
1630932870210
2021-09-06 18:54:30
1630932872655
2021-09-06 18:54:32
1630932800127
2021-09-06 18:53:20
Sabil
  • 3,750
  • 1
  • 5
  • 16