From 9d2e22a24685ad21faf47513f7709555682da88e Mon Sep 17 00:00:00 2001 From: Eoghan Glynn Date: Mon, 20 Feb 2012 09:57:04 +0000 Subject: Promote more complete support for ISO 8601 time. Support for ISO 861 time representation is now duplicated in nova: https://github.com/openstack/nova/commit/c30193fbf and in glance: https://github.com/openstack/glance/commit/f8f9f171 Note this patch introduces a new dependency on python-iso8601, which has already been packaged for Fedora, EPEL and Ubuntu/Debian. Change-Id: I87c32effa97d3b7a8d869522b62c0c6fb31bcef8 --- openstack/common/utils.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'openstack') diff --git a/openstack/common/utils.py b/openstack/common/utils.py index 9b30020..3a0e6c6 100644 --- a/openstack/common/utils.py +++ b/openstack/common/utils.py @@ -28,11 +28,12 @@ import sys from eventlet import greenthread from eventlet.green import subprocess +import iso8601 from openstack.common import exception -TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" +TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" LOG = logging.getLogger(__name__) @@ -163,13 +164,29 @@ def import_object(import_str): def isotime(at=None): + """Stringify time in ISO 8601 format""" if not at: at = datetime.datetime.utcnow() - return at.strftime(TIME_FORMAT) + str = at.strftime(TIME_FORMAT) + tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' + str += ('Z' if tz == 'UTC' else tz) + return str def parse_isotime(timestr): - return datetime.datetime.strptime(timestr, TIME_FORMAT) + """Parse time from ISO 8601 format""" + try: + return iso8601.parse_date(timestr) + except iso8601.ParseError as e: + raise ValueError(e.message) + except TypeError as e: + raise ValueError(e.message) + + +def normalize_time(timestamp): + """Normalize time in arbitrary timezone to UTC""" + offset = timestamp.utcoffset() + return timestamp.replace(tzinfo=None) - offset if offset else timestamp def utcnow(): -- cgit