Using Coinmarketcap Pro and CryptoCompare APIs around manipulating timestamps in Python

Image for post
Image for post

Checking your system timezone

Before we manipulate time in Python, make sure you know which timezone your system is running:

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

Converting a timestamp from a Coinmarketcap Pro API call

Let’s move onto a real world example of fetching an API response where a timestamp is a necessity to store or manipulate. In this case let’s use the new Coinmarketcap Pro API to fetch the latest Bitcoin prices.

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

Once a datetime object has been initialised we can then format and manipulate it in any way we see fit.

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

Let’s look at another real world example. Let’s get yesterday’s open, high, low and close prices of Bitcoin:

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

Sometimes we want to generate another date relative to a timestamp, such as tomorrows date, or yesterdays date, perhaps if my supervisor is doing a range of chores based on yesterdays tasks. timedelta can be used for this:

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

Where to go from here

Both CryptoCompare and Coinmarketcap Pro offer free API services for you to play with.

Programmer and Author. Director @ JKRBInvestments.com. Creator of ChineseGrammarReview.app 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