1
# Copyright 2011 OpenStack Foundation.
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
5
# not use this file except in compliance with the License. You may obtain
6
# a copy of the License at
8
# http://www.apache.org/licenses/LICENSE-2.0
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
# License for the specific language governing permissions and limitations
17
Time related utilities and helper functions.
28
# ISO 8601 extended time format with microseconds
29
_ISO8601_TIME_FORMAT_SUBSECOND = '%Y-%m-%dT%H:%M:%S.%f'
30
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
31
PERFECT_TIME_FORMAT = _ISO8601_TIME_FORMAT_SUBSECOND
34
def isotime(at=None, subsecond=False):
35
"""Stringify time in ISO 8601 format."""
38
st = at.strftime(_ISO8601_TIME_FORMAT
40
else _ISO8601_TIME_FORMAT_SUBSECOND)
41
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
42
st += ('Z' if tz == 'UTC' else tz)
46
def parse_isotime(timestr):
47
"""Parse time from ISO 8601 format."""
49
return iso8601.parse_date(timestr)
50
except iso8601.ParseError as e:
51
raise ValueError(six.text_type(e))
52
except TypeError as e:
53
raise ValueError(six.text_type(e))
56
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
57
"""Returns formatted utcnow."""
60
return at.strftime(fmt)
63
def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT):
64
"""Turn a formatted time back into a datetime."""
65
return datetime.datetime.strptime(timestr, fmt)
68
def normalize_time(timestamp):
69
"""Normalize time in arbitrary timezone to UTC naive object."""
70
offset = timestamp.utcoffset()
73
return timestamp.replace(tzinfo=None) - offset
76
def is_older_than(before, seconds):
77
"""Return True if before is older than seconds."""
78
if isinstance(before, six.string_types):
79
before = parse_strtime(before).replace(tzinfo=None)
81
before = before.replace(tzinfo=None)
83
return utcnow() - before > datetime.timedelta(seconds=seconds)
86
def is_newer_than(after, seconds):
87
"""Return True if after is newer than seconds."""
88
if isinstance(after, six.string_types):
89
after = parse_strtime(after).replace(tzinfo=None)
91
after = after.replace(tzinfo=None)
93
return after - utcnow() > datetime.timedelta(seconds=seconds)
97
"""Timestamp version of our utcnow function."""
98
if utcnow.override_time is None:
99
# NOTE(kgriffs): This is several times faster
100
# than going through calendar.timegm(...)
101
return int(time.time())
103
return calendar.timegm(utcnow().timetuple())
107
"""Overridable version of utils.utcnow."""
108
if utcnow.override_time:
110
return utcnow.override_time.pop(0)
111
except AttributeError:
112
return utcnow.override_time
113
return datetime.datetime.utcnow()
116
def iso8601_from_timestamp(timestamp):
117
"""Returns an iso8601 formatted date from timestamp."""
118
return isotime(datetime.datetime.utcfromtimestamp(timestamp))
121
utcnow.override_time = None
124
def set_time_override(override_time=None):
125
"""Overrides utils.utcnow.
127
Make it return a constant time or a list thereof, one at a time.
129
:param override_time: datetime instance or list thereof. If not
130
given, defaults to the current UTC time.
132
utcnow.override_time = override_time or datetime.datetime.utcnow()
135
def advance_time_delta(timedelta):
136
"""Advance overridden time using a datetime.timedelta."""
137
assert utcnow.override_time is not None
139
for dt in utcnow.override_time:
142
utcnow.override_time += timedelta
145
def advance_time_seconds(seconds):
146
"""Advance overridden time by seconds."""
147
advance_time_delta(datetime.timedelta(0, seconds))
150
def clear_time_override():
151
"""Remove the overridden time."""
152
utcnow.override_time = None
155
def marshall_now(now=None):
156
"""Make an rpc-safe datetime with microseconds.
158
Note: tzinfo is stripped, but not required for relative times.
162
return dict(day=now.day, month=now.month, year=now.year, hour=now.hour,
163
minute=now.minute, second=now.second,
164
microsecond=now.microsecond)
167
def unmarshall_time(tyme):
168
"""Unmarshall a datetime dict."""
169
return datetime.datetime(day=tyme['day'],
173
minute=tyme['minute'],
174
second=tyme['second'],
175
microsecond=tyme['microsecond'])
178
def delta_seconds(before, after):
179
"""Return the difference between two timing objects.
181
Compute the difference in seconds between two date, time, or
182
datetime objects (as a float, to microsecond resolution).
184
delta = after - before
185
return total_seconds(delta)
188
def total_seconds(delta):
189
"""Return the total seconds of datetime.timedelta object.
191
Compute total seconds of datetime.timedelta, datetime.timedelta
192
doesn't have method total_seconds in Python2.6, calculate it manually.
195
return delta.total_seconds()
196
except AttributeError:
197
return ((delta.days * 24 * 3600) + delta.seconds +
198
float(delta.microseconds) / (10 ** 6))
201
def is_soon(dt, window):
202
"""Determines if time is going to happen in the next window seconds.
205
:param window: minimum seconds to remain to consider the time not soon
207
:return: True if expiration is within the given duration
209
soon = (utcnow() + datetime.timedelta(seconds=window))
210
return normalize_time(dt) <= soon