Skip to content

Instantly share code, notes, and snippets.

@zed
Last active September 4, 2019 16:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/9ac31afbd20c5c287315 to your computer and use it in GitHub Desktop.
Save zed/9ac31afbd20c5c287315 to your computer and use it in GitHub Desktop.
next leap second IERS-OP web service client
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv
venv/
ENV/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/

Python client for IERS-OP web service

It answers the following questions:

  • What is the current difference between TAI and UTC?
  • When was the last leap second?
  • When is the next leap second?

Usage

As a library:

>>> from leap_second_client import request_leap_second_info
>>> request_leap_second_info()
LeapSecondInfo(TAI_UTC=36,
               last_leap_second=datetime.date(2015, 6, 30),
               next_leap_second=None)

Or as a command-line client (greppable json output):

$ python -m leap_second_client
{
    "TAI_UTC": 36,
    "last_leap_second": "2015-06-30",
    "next_leap_second": null
}

It gives the current value of TAI-UTC in (integer) seconds, the date of the last leap second and the date of the next leap second. If no leap second is scheduled, then the value is None. The webservice relies on the information of the last Bulletin C and the current date.

See http://hpiers.obspm.fr/eop-pc/index.php?index=webservice

Installation

No dependencies except Python itself and the webservice. To install, just download leap_second_client.py or run:

$ pip install leap_second_client

Support: Python 2.6+, Python 3.

License: MIT

#!/usr/bin/env python
"""Python client for IERS-OP WEB SERVICE.
As a library:
>>> from leap_second_client import request_leap_second_info
>>> request_leap_second_info()
LeapSecondInfo(TAI_UTC=36,
last_leap_second=datetime.date(2015, 6, 30),
next_leap_second=None)
Or as a command-line client (greppable json output):
$ python -m leap_second_client
{
"TAI_UTC": 36,
"last_leap_second": "2015-06-30",
"next_leap_second": null
}
It gives the current value of TAI-UTC in (integer) seconds, the date
of the last leap second and the date of the next leap second. If no
leap second is scheduled, then the value is None. The webservice
relies on the information of the last Bulletin C and the current date.
See http://hpiers.obspm.fr/eop-pc/index.php?index=webservice
No dependencies except Python itself and the webservice.
To install, just download leap_second_client.py.
Support: Python 2.6+, Python 3.
"""
import json
import platform
import xml.etree.ElementTree as etree
from collections import namedtuple
from datetime import datetime
try:
from urllib.request import urlopen, Request
except ImportError: # Python 2
from urllib2 import urlopen, Request
__all__ = ['request_leap_second_info']
__version__ = '1.0'
LeapSecondInfo = namedtuple('LeapSecondInfo',
'TAI_UTC last_leap_second next_leap_second')
_url = "http://hpiers.obspm.fr/eop-pc/webservice/leap_second_server.php"
_user_agent = 'leap_second_client/%s %s/%s' % (
__version__,
platform.python_implementation(),
platform.python_version())
_headers = {
'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': '"http://hpiers.obspm.fr/eop-pc/webservice/'
'leap_second_server.php/LeapSecond"',
'User-Agent': _user_agent,
}
_data = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ns0="http://hpiers.obspm.fr/eop-pc/webservice/"
xmlns:ns1="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Header/>
<ns2:Body>
<ns0:LeapSecond/>
</ns2:Body>
</SOAP-ENV:Envelope>
'''.encode()
def _parse_date(webservice_date_string):
return datetime.strptime(webservice_date_string, '%d %B %Y').date()
def _parse_next_leap_date(webservice_date_string):
return datetime.strptime(webservice_date_string, '%Y %B %d, 23h 59m 60s').date()
def request_leap_second_info():
"""Make request to the IERS-OP leap second webservice."""
response = etree.parse(urlopen(Request(_url, _data, _headers)))
next_leap_second = response.findtext('.//Next_leap_second')
if next_leap_second != "Not scheduled":
next_leap_second = _parse_next_leap_date(next_leap_second)
else:
next_leap_second = None
return LeapSecondInfo(
TAI_UTC=int(response.findtext('.//TAI_UTC')),
last_leap_second=_parse_date(response.findtext('.//Last_leap_second')),
next_leap_second=next_leap_second)
def main():
print(json.dumps(request_leap_second_info()._asdict(),
indent=4, default=str, sort_keys=True))
if __name__ == "__main__":
main()
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
include README.rst LICENSE
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# From: https://github.com/kennethreitz/setup.py
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import re
import sys
from shutil import rmtree
from setuptools import setup, Command
# Package meta-data.
NAME = 'leap_second_client'
DESCRIPTION = 'Find the next leap second using IERS-OP web service.'
URL = 'https://github.com/zed/leap-second-client'
EMAIL = 'isidore.john.r@gmail.com'
AUTHOR = 'zed'
# What packages are required for this module to be executed?
REQUIRED = [
# 'requests', 'maya', 'records',
]
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
def read_version(filename):
with open(filename, 'rb') as file:
source = file.read().decode('utf-8')
return re.search(r'(?m)^__version__ = ([\'"])(.+?)\1', source).group(2)
# Load the package's __version__.py module as a dictionary.
about = {'__version__': read_version(os.path.join(here, NAME + '.py'))}
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system(
'{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPi via Twine…')
os.system('twine upload dist/*')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
author=AUTHOR,
author_email=EMAIL,
url=URL,
# packages=find_packages(exclude=('tests',)),
# If your package is a single module, use this instead of 'packages':
py_modules=[NAME],
entry_points={
'console_scripts': ['leap-second-client=leap_second_client:main'],
},
install_requires=REQUIRED,
include_package_data=True,
license='MIT',
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment