Skip to content

Instantly share code, notes, and snippets.

@pbannister
Created June 16, 2016 15:37
Show Gist options
  • Save pbannister/aa71e643a0be525ec01d8f63564700f8 to your computer and use it in GitHub Desktop.
Save pbannister/aa71e643a0be525ec01d8f63564700f8 to your computer and use it in GitHub Desktop.
"""
Handle timestamps as used in OpenStack.
In theory, timestamps from OpenStack are going to be ISO datetime.
In practice, timestamps from OpenStack are likely always UTC.
At present, timestamps from Keystone all(?) end in 'Z'.
At present, timestamps from Cinder all(?) lack any timezone/offset.
Beware of Python "naive" datetime (w/o timezome).
Forms expected:
2016-06-01T11:22:33.12345Z
2016-06-01T11:22:33.12345
2016-06-01T11:22:33.12345+12:23 (not handled)
2016-06-01T11:22:33.12345-12:23 (not handled)
Add common handling of OpenStack timestamps here, as needed.
Returned datetime values are UTC and "naive".
"""
import datetime
# import re
_ISO8601_DATETIME = '%Y-%m-%dT%H:%M:%S.%f'
_ISO8601_Z = _ISO8601_DATETIME + 'Z'
# Not supported in Python 2.7 - despite the documentation.
# _ISO8601_OFFSET = _ISO8601_DATETIME + '%z'
def isotime_parse(s):
""" Common parsing for OpenStack ISO format timestamps.
"""
# What we expect from OpenStack.
if 'Z' in s:
return datetime.datetime.strptime(s, _ISO8601_Z)
# This is an ISO time with an offset.
# if ('+' in s) or ('-' in s):
# # Convert the ISO offset (if present) into a form strptime handles.
# s = re.sub('([-+]\d\d):(\d\d)', '\\1\\2', s)
# return datetime.datetime.strptime(s, _ISO8601_OFFSET)
# Assume we are getting a time w/o an offset.
return datetime.datetime.strptime(s, _ISO8601_DATETIME)
def isotime_now():
""" What we should always use for "now" with parsed timestamps.
"""
return datetime.datetime.utcnow()
def main():
v = isotime_now()
print "{} is now (as naive)".format(v)
print "{} is now (as isoformat)".format(v.isoformat())
a = [
"2016-06-01T11:22:33.12345Z",
"2016-06-01T11:22:33.12346",
"2016-06-01T11:22:33.12347+12:34",
"2016-06-01T11:22:33.12348-12:34",
"2016-06-01T11:22:33.12349bogus",
"2016-06-01T11:22:34"
]
for v1 in a:
try:
v2 = isotime_parse(v1)
print "{} as naive {}".format(v1, v2)
print "{} as isoformat {}".format(v1, v2.isoformat())
except Exception as e:
print "Exception: {}".format(e)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment