Using Coinmarketcap Pro and CryptoCompare APIs around manipulating timestamps in Python

Checking your system timezone

import timeprint(time.tzname)
print(time.time())
> [UTC, UTC]
sudo timedatectl set-timezone UTC

Converting a timestamp from a Coinmarketcap Pro API call

import time, requests, json
import datetime as dt
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD'headers = {
'Accept': 'application/json',
'Accept-Encoding': 'deflate, gzip',
'X-CMC_PRO_API_KEY': COINMARKETCAP_PRO_API_KEY,
}
r = requests.get(url, headers=headers)if r.status_code == 200:
response = json.loads(r.text)
{'status': 
{
'timestamp': '2018-08-09T07:26:22.078Z',
...

'data': {
'BTC': {
'date_added': '2013-04-28T00:00:00.000Z',
'last_updated': '2018-08-09T07:25:31.000Z'
...
}
}
}
}
...lastUpdated = response['data']['BTC']['quote']['USD']['last_updated']timestamp = dt.datetime.strptime(lastUpdated, '%Y-%m-%dT%H:%M:%S.000Z')print(timestamp)> 2018-08-09 07:25:31

Converting timestamps to other formats

lastUpdatedUnix = int(lastUpdatedDt.strftime("%s"))
dateOnly = str(lastUpdatedDt.strftime("%Y-%m-%d"))print(dateOnly)> 2018-08-09dateOnlyUnix = dt.datetime.strptime(lastUpdated, "%s");

Converting a timestamp from a CryptoCompare API call

request = requests.get('https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD')if request.content != '':
response = request.content
response = json.loads(response)
print(response)
{ 
'Response': 'Success',
...
'Data': [
{
'time': 1531180800
...
},
...
]
}
dayIndex = len(response['Data']) - 2

time = int(response['Data'][dayIndex]['time'])
priceHigh = float(response['Data'][dayIndex]['high'])
priceLow = float(response['Data'][dayIndex]['low'])
priceOpen = float(response['Data'][dayIndex]['open'])
priceClose = float(response['Data'][dayIndex]['close'])
priceTime = float(response['Data'][dayIndex]['time'])
timestampDateOnly = dt.datetime.utcfromtimestamp(time).strftime("%d/%m/%Y")print(timestampDateOnly)> 08/08/2018

Adding and Subtracting time using Timedelta

...
from datetime import timedelta
today = 1533781210tomorrow = dt.datetime.utcfromtimestamp(today) + timedelta(days=1)tomorrow = tomorrow.strftime("%d/%m/%Y")

Where to go from here

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store