Search code examples
pythonunix-timestamppython-datetime

Unable to convert unix timestamp in date format


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.


Solution

  • 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