Skip to content

Instantly share code, notes, and snippets.

@HeinrichHartmann
Last active Aug 29, 2015
Embed
What would you like to do?
WorldCupTime
#!/usr/bin/python
import sys
import BaseHTTPServer
import urllib2
from dateutil import parser, tz as dutz
from datetime import datetime, tzinfo
import ipdb
BREAK=ipdb.set_trace
from SimpleHTTPServer import SimpleHTTPRequestHandler
from string import Template
TEMPLATE = Template(r"""
<html>
<head><title>World Champion Time</title>
<style>
body {
background-color: #FFFFFF;
text-align: center;
font-size: 12pt;
}
h1 {
font-size: 30pt;
}
h3 {
font-size: 20pt;
margin: 5px;
}
</style>
</head>
<body><h1><font color="#000000">World</font> <font color="#FF0000">Champion</font> <font color="#EEBB00">Time</font>
<br><h3>$TIME</h3>
<br><h3>Measured since the World Cup Final 2014</h3>
<br>
<br><img src="http://upload.wikimedia.org/wikipedia/en/thumb/e/e8/WC-2014-Brasil.svg/200px-WC-2014-Brasil.svg.png"\>
<br>
<br><form><input type="text" name="q" value="14 July 2014"><button type="submit" text="query">Convert</button></form>
<br>$CONVERT</br>
<br>
<br>
<br>Image taken from <a href="http://en.wikipedia.org/wiki/File:WC-2014-Brasil.svg"> Wikipedia </a> under <a href="http://en.wikipedia.org/wiki/Fair_use">fair use</a>.
<br>source code <a href="https://gist.github.com/HeinrichHartmann/f581e16757c61be38aed">gist</a>
<br>by <a href="/">Heinrich Hartmann</a>
</body>
</html>
""")
import urlparse
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_GET(s):
"""Respond to a GET request."""
parsed_path = urlparse.urlparse(s.path)
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write(TEMPLATE.substitute(TIME=nowWCT(), CONVERT=Convert(parsed_path.query)))
import pytz
UTC = pytz.utc
CEST = pytz.timezone("Europe/Berlin")
WCT_START = datetime(2013,07,13,23,00,00,tzinfo=UTC)
YZERO = 2014
DT_ZERO = datetime(YZERO,1,1,0,0,tzinfo=UTC)
def nowWCT():
return formatWCT(datetime.now(UTC))
def formatWCT(dt):
"""
dt -- aware datetime object (perferably in utc)
"""
y,m,d,H,M,S = toWCT(dt)
fmt_y = lambda y : ("-" if y < 0 else "") + "{:04d}".format(abs(y))
return "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} WCT".format(fmt_y(y),m,d,H,M,S)
def toWCT(dt):
"""
dt -- date aware datetime object
"""
print "toWCT", dt
WCT_2K = CEST.normalize((DT_ZERO + (dt - WCT_START)).astimezone(CEST))
return (WCT_2K.year - YZERO, WCT_2K.month, WCT_2K.day, WCT_2K.hour, WCT_2K.minute, WCT_2K.second)
### REVERSE CONVERSION
import re
r = r'([-]?\d+)-(\d+)-(\d+)\s?(\d+)?(:\d+)?(:\d+)?'
def fromWCT(q):
"""
q -- date string
returns aware datetime object
"""
Y,M,D,h,m,s = re.findall(r,q)[0]
m = m.strip(":")
s = s.strip(":")
toint = lambda s : 0 if not s else int(s)
wct2k = CEST.localize(datetime(
toint(Y) + YZERO,
toint(M),
toint(D), toint(h), toint(m), toint(s)))
dt = wct2k + (WCT_START - DT_ZERO)
return CEST.normalize(dt)
import traceback
import urlparse
def Convert(s):
"""
Example:
s = "q=0000-01-02+15%3A48%3A19+WCT+"
"""
q_dict = urlparse.parse_qs(s)
q = "14 July 2014"
if "q" in q_dict.keys():
q = q_dict["q"][0]
try:
if q.endswith("WCT"):
res = fromWCT(q).strftime("%Y-%m-%d %H:%M:%S %Z")
else:
dt = parser.parse(q)
if dt.tzinfo == None:
dt = CEST.localize(dt)
dt = UTC.normalize(dt.astimezone(pytz.UTC))
res = formatWCT(dt)
except:
traceback.print_exc()
return ""
return q + " is " + res
def main():
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('0.0.0.0', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, MyHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment