This repository was archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtime_util.py
382 lines (306 loc) · 9.93 KB
/
time_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Roland Hedberg, Sweden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Implements some useful functions when dealing with validity of
different types of information.
"""
import calendar
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import logging
import re
import time
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
TIME_FORMAT_WITH_FRAGMENT = re.compile("^(\d{4,4}-\d{2,2}-\d{2,2}T\d{2,2}:\d{2,2}:\d{2,2})\.\d*Z$")
logger = logging.getLogger(__name__)
class TimeUtilError(Exception):
pass
# ---------------------------------------------------------------------------
# I'm sure this is implemented somewhere else can't find it now though, so I
# made an attempt.,
# Implemented according to
# http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/
# adding-durations-to-dateTimes
def f_quotient(arg0, arg1, arg2=0):
if arg2:
return int((arg0 - arg1) // (arg2 - arg1))
elif not arg0:
return 0
else:
return int(arg0 // arg1)
def modulo(arg0, arg1, arg2=0):
if arg2:
return ((arg0 - arg1) % (arg2 - arg1)) + arg1
else:
return arg0 % arg1
def maximum_day_in_month_for(year, month):
return calendar.monthrange(year, month)[1]
D_FORMAT = [
("Y", "tm_year"),
("M", "tm_mon"),
("D", "tm_mday"),
("T", None),
("H", "tm_hour"),
("M", "tm_min"),
("S", "tm_sec"),
]
def parse_duration(duration):
# (-)PnYnMnDTnHnMnS
index = 0
if duration[0] == "-":
sign = "-"
index += 1
else:
sign = "+"
if duration[index] != "P":
raise ValueError('duration index {} != "P"'.format(duration[index]))
index += 1
dic = dict([(typ, 0) for (code, typ) in D_FORMAT])
for code, typ in D_FORMAT:
# print duration[index:], code
if duration[index] == "-":
raise TimeUtilError("Negation not allowed on individual items")
if code == "T":
if duration[index] == "T":
index += 1
if index == len(duration):
raise TimeUtilError("Not allowed to end with 'T'")
else:
raise TimeUtilError("Missing T")
else:
try:
mod = duration[index:].index(code)
try:
dic[typ] = int(duration[index : index + mod])
except ValueError:
if code == "S":
try:
dic[typ] = float(duration[index : index + mod])
except ValueError:
raise TimeUtilError("Not a float")
else:
raise TimeUtilError("Fractions not allow on anything byt seconds")
index = mod + index + 1
except ValueError:
dic[typ] = 0
if index == len(duration):
break
return sign, dic
def add_duration(tid, duration):
(sign, dur) = parse_duration(duration)
if sign == "+":
# Months
temp = tid.tm_mon + dur["tm_mon"]
month = modulo(temp, 1, 13)
carry = f_quotient(temp, 1, 13)
# Years
year = tid.tm_year + dur["tm_year"] + carry
# seconds
temp = tid.tm_sec + dur["tm_sec"]
secs = modulo(temp, 60)
carry = f_quotient(temp, 60)
# minutes
temp = tid.tm_min + dur["tm_min"] + carry
minutes = modulo(temp, 60)
carry = f_quotient(temp, 60)
# hours
temp = tid.tm_hour + dur["tm_hour"] + carry
hour = modulo(temp, 60)
carry = f_quotient(temp, 60)
# days
if dur["tm_mday"] > maximum_day_in_month_for(year, month):
temp_days = maximum_day_in_month_for(year, month)
elif dur["tm_mday"] < 1:
temp_days = 1
else:
temp_days = dur["tm_mday"]
days = temp_days + tid.tm_mday + carry
while True:
if days < 1:
pass
elif days > maximum_day_in_month_for(year, month):
days -= maximum_day_in_month_for(year, month)
carry = 1
else:
break
temp = month + carry
month = modulo(temp, 1, 13)
year += f_quotient(temp, 1, 13)
return time.localtime(time.mktime((year, month, days, hour, minutes, secs, 0, 0, -1)))
else:
pass
# ---------------------------------------------------------------------------
def time_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
"""
Will return a time specification for a time sometime in the future.
:return: datetime instance using UTC time
"""
delta = timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
res = datetime.now(timezone.utc) + delta
return res.replace(tzinfo=None)
def time_a_while_ago(
days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0
):
"""
Will return a time specification for a time sometime in the past.
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param hours:
:param weeks:
:return: datetime instance using UTC time
"""
delta = timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
res = datetime.now(timezone.utc) - delta
return res.replace(tzinfo=None)
def in_a_while(
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0,
time_format=TIME_FORMAT,
):
"""
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param hours:
:param weeks:
:param time_format:
:return: Formatet string
"""
if not time_format:
time_format = TIME_FORMAT
return time_in_a_while(
days, seconds, microseconds, milliseconds, minutes, hours, weeks
).strftime(time_format)
def a_while_ago(
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0,
time_format=TIME_FORMAT,
):
"""
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param hours:
:param weeks:
:param time_format:
:return: Formatet string
"""
return time_a_while_ago(
days, seconds, microseconds, milliseconds, minutes, hours, weeks
).strftime(time_format)
# ---------------------------------------------------------------------------
def shift_time(dtime, shift):
"""Adds/deletes an integer amount of seconds from a datetime specification
:param dtime: The datatime specification
:param shift: The wanted time shift (+/-)
:return: A shifted datatime specification
"""
return dtime + timedelta(seconds=shift)
# ---------------------------------------------------------------------------
def str_to_time(timestr, time_format=TIME_FORMAT):
"""
:param timestr:
:param time_format:
:return: UTC time
"""
if not timestr:
return 0
try:
then = time.strptime(timestr, time_format)
except ValueError: # assume it's a format problem
try:
elem = TIME_FORMAT_WITH_FRAGMENT.match(timestr)
except Exception as exc:
logger.error("Exception: %s on %s" % (exc, timestr))
raise
then = time.strptime(elem.groups()[0] + "Z", TIME_FORMAT)
return time.gmtime(calendar.timegm(then))
def instant(time_format=TIME_FORMAT):
return time.strftime(time_format, time.gmtime())
# ---------------------------------------------------------------------------
def before(point):
""" True if point datetime specification is before now """
if not point:
return True
if isinstance(point, str):
point = str_to_time(point)
elif isinstance(point, int):
point = time.gmtime(point)
return time.gmtime() < point
def after(point):
""" True if point datetime specification is equal or after now """
if not point:
return True
else:
return not before(point)
not_before = after
# 'not_on_or_after' is just an obscure name for 'before'
not_on_or_after = before
# a point is valid if it is now or sometime in the future, in other words,
# if it is not before now
valid = before
def later_than(after, before):
""" True if then is later or equal to that """
if isinstance(after, str):
after = str_to_time(after)
elif isinstance(after, int):
after = time.gmtime(after)
if isinstance(before, str):
before = str_to_time(before)
elif isinstance(before, int):
before = time.gmtime(before)
return after >= before
def utc_time_sans_frac(): # MUST be the same as utc_time_sans_frac in cryptojwt
now_timestampt = int(datetime.now(timezone.utc).timestamp())
return now_timestampt
def time_sans_frac():
return int("%d" % time.time())
def epoch_in_a_while(
days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0
):
"""
Return the number of seconds since epoch a while from now.
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param hours:
:param weeks:
:return: Seconds since epoch (1970-01-01)
"""
dt = time_in_a_while(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
dt_timestamp = int(dt.timestamp())
return dt_timestamp