Last active
January 19, 2016 04:09
-
-
Save MichaelCurrie/fa4096710ef6c6ae65b0 to your computer and use it in GitHub Desktop.
ISO 8601 UTC timestamp recipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Here we use timezone-aware datetime objects, as opposed to timezone-naive ones. | |
Source: Python manuals, stackoverflow posts, trial and error. | |
""" | |
from datetime import datetime | |
import time | |
import pytz | |
import dateutil.parser | |
# i.e. datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>) | |
epoch = datetime.fromtimestamp(0, pytz.utc) | |
# e.g. 1453173767.139255 | |
seconds_since_UNIX_epoch = time.time() | |
# e.g. datetime.datetime(2016, 1, 19, 3, 22, 47, 139255, tzinfo=tzutc()) | |
timestamp = datetime.fromtimestamp(seconds_since_UNIX_epoch, pytz.utc) | |
# e.g. '2016-01-19T03:22:47.139255+00:00' | |
iso_timestamp_string = timestamp.isoformat() | |
# e.g. datetime.datetime(2016, 1, 19, 3, 22, 47, 139255, tzinfo=tzutc()) | |
back_again = dateutil.parser.parse(iso_timestamp_string) | |
# A time_delta object: datetime.timedelta(16819, 12167, 139255) | |
td = (back_again - epoch) | |
# e.g. 1453173767.139254 | |
td_seconds = td.total_seconds() | |
# CHECK: | |
# Verify that we got back to where we started | |
# Use approximate check because of floating point epsilon as per | |
# https://www.python.org/dev/peps/pep-0485/ | |
import sys | |
if sys.version_info[0] >= 3 and sys.version_info[1] >= 5: | |
from math import isclose | |
else: | |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): | |
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) | |
assert(isclose(seconds_since_UNIX_epoch, td_seconds)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment