Skip to content

Instantly share code, notes, and snippets.

@nick3499
Last active October 19, 2021 06:47
Show Gist options
  • Save nick3499/8ab30d36658f7734d0578e41cceabf0b to your computer and use it in GitHub Desktop.
Save nick3499/8ab30d36658f7734d0578e41cceabf0b to your computer and use it in GitHub Desktop.
Python 3: Get astronomy data from IPGeolocation’s Astronomy API: requests, json, pendulum
#!/bin/python3
'''Get data from IPGeolocation’s Astronomy API.'''
from json import loads
from requests import get
from pendulum import parse
# API key
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# geolocation
LATITUDE = '40.713'
LONGITUDE = '-74.0072'
# source website
URL = f'https://api.ipgeolocation.io/astronomy?apiKey={API_KEY}&lat={LATITUDE}\
&long={LONGITUDE}'
# browser header
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, \
like Gecko) Chrome/96.0.4664.9 Safari/537.36'}
# server request
response = get(URL, headers=headers).text
# dictionary
data = loads(response)
# color dictionary
dark_orange = f'\x1b[1;7;38;5;208m'
orange_1 = f'\x1b[1;7;38;5;214m'
gold_1 = f'\x1b[1;7;38;5;220m'
yellow_1 = f'\x1b[1;7;38;5;226m'
reset = f'\x1b[0m'
# date/time
print(f"{dark_orange} Date {reset} \
{parse(data['date'], exact=True).format('dddd, MMMM DD, YYYY')}")
print(f"{dark_orange} Time {reset} \
{parse(data['current_time'], exact=True).format('h:mm:ss A')}")
# sunrise/sunset
print(f"{orange_1} Sunrise {reset} \
{parse(data['sunrise'], exact=True).format('h:mm A')}")
print(f"{orange_1} Sunset {reset} \
{parse(data['sunset'], exact=True).format('h:mm A')}")
# length of day
print(f"{gold_1} Day length {reset} {data['day_length']}")
# moonrise/moonset
print(f"{yellow_1} Moonrise {reset} \
{parse(data['moonrise'], exact=True).format('h:mm A')}")
print(f"{yellow_1} Moonset {reset} \
{parse(data['moonset'], exact=True).format('h:mm A')}")
@nick3499
Copy link
Author

nick3499 commented Oct 17, 2021

Notes:

  • requests and json modules should already be installed, but pendulum needs to be installed.
  • IPGeolocation.io offers free API keys.
  • the geolocation used in this script is only for example.
  • use Google keywordsmy headers’ to find a website that returns your browser’s 'User-Agent' header. Once found, use it in place of the header shown in this script in order to reflect your browser's current header. That header is used to imitate a browser request, just as your browser would be returning that header otherwise.
  • requests module is used to request data from a server.
  • json handles data in JSON format.
  • pendulum module simplifies the tedious datetime module.
  • color names come from 256 COLORS - CHEAT SHEET

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment