1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2011 OpenStack LLC.
6
# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
# not use this file except in compliance with the License. You may obtain
8
# a copy of the License at
10
# http://www.apache.org/licenses/LICENSE-2.0
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
# License for the specific language governing permissions and limitations
19
Time related utilities and helper functions.
29
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
30
PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
34
"""Stringify time in ISO 8601 format"""
37
str = at.strftime(TIME_FORMAT)
38
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
39
str += ('Z' if tz == 'UTC' else tz)
43
def parse_isotime(timestr):
44
"""Parse time from ISO 8601 format"""
46
return iso8601.parse_date(timestr)
47
except iso8601.ParseError as e:
48
raise ValueError(e.message)
49
except TypeError as e:
50
raise ValueError(e.message)
53
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
54
"""Returns formatted utcnow."""
57
return at.strftime(fmt)
60
def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT):
61
"""Turn a formatted time back into a datetime."""
62
return datetime.datetime.strptime(timestr, fmt)
65
def normalize_time(timestamp):
66
"""Normalize time in arbitrary timezone to UTC"""
67
offset = timestamp.utcoffset()
68
return timestamp.replace(tzinfo=None) - offset if offset else timestamp
71
def is_older_than(before, seconds):
72
"""Return True if before is older than seconds."""
73
return utcnow() - before > datetime.timedelta(seconds=seconds)
77
"""Timestamp version of our utcnow function."""
78
return calendar.timegm(utcnow().timetuple())
82
"""Overridable version of utils.utcnow."""
83
if utcnow.override_time:
84
return utcnow.override_time
85
return datetime.datetime.utcnow()
88
utcnow.override_time = None
91
def set_time_override(override_time=datetime.datetime.utcnow()):
92
"""Override utils.utcnow to return a constant time."""
93
utcnow.override_time = override_time
96
def advance_time_delta(timedelta):
97
"""Advance overriden time using a datetime.timedelta."""
98
assert(not utcnow.override_time is None)
99
utcnow.override_time += timedelta
102
def advance_time_seconds(seconds):
103
"""Advance overriden time by seconds."""
104
advance_time_delta(datetime.timedelta(0, seconds))
107
def clear_time_override():
108
"""Remove the overridden time."""
109
utcnow.override_time = None