-
Notifications
You must be signed in to change notification settings - Fork 1
/
kron.py
executable file
·710 lines (604 loc) · 21.8 KB
/
kron.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
#!/usr/bin/env python
# Name: kron
# Description: Uniform interface for dates and times
# Version: 1.6.12
# File: kron.py
# Author: qtfkwk <qtfkwk+kron@gmail.com>
# Copyright: (C) 2016 by qtfkwk
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
"""Uniform interface for dates and times
* Documentation: https://kron.readthedocs.io
* API Reference: https://kron.readthedocs.io/#id9
"""
from __future__ import division
from __future__ import print_function
from past.builtins import cmp
from builtins import object
# Standard modules
import argparse
import datetime
import json
import re
import calendar
# External modules
import ntplib
import pytz
import tzlocal
# Variables
__version__ = '1.6.12'
# Classes
class duration(object):
"""Represents a duration of time
``value`` is float seconds.
Internal storage is float seconds and accessible via the ``value``
property.
Duration objects can be compared via ``<``, ``>``, ``<=``, ``>=``,
``==``, and ``!=`` with each other or an int/float value in
seconds.
Duration objects support various arithmetic operations via ``+``,
``-``, ``*``, ``/``.
+----------+----------------------+---------------+
| Operator | Other type | Returned type |
+==========+======================+===============+
| ``+`` | timestamp | timestamp |
+ +----------------------+---------------+
| | int, float, duration | duration |
+----------+----------------------+---------------+
| ``-`` | int, float, duration | duration |
+----------+----------------------+---------------+
| ``*`` | int, float | duration |
+----------+----------------------+---------------+
| ``/`` | int, float | duration |
+----------+----------------------+---------------+
Arithmetic operations with a type not listed in the above table
raises one of ``DurationAddError``, ``DurationDivideError``,
``DurationMultipyError``, or ``DurationSubtractError``.
"""
_units = ('days', 'hours', 'minutes', 'seconds')
_values = dict(days=86400, hours=3600, minutes=60, seconds=1)
def __init__(self, value=0):
self.value = float(round(value, 6))
def dict(self):
"""Returns a dictionary with the duration as the count of
days, hours, minutes, seconds, and microseconds"""
v = int(self.value)
r = dict(days=0, hours=0, minutes=0, seconds=0)
r['microseconds'] = int((self.value - v) * 10**6 + 0.5)
for i in self._units:
r[i] = v // self._values[i]
v -= r[i] * self._values[i]
return r
def __cmp__(self, y):
"""Compare two duration objects"""
if isinstance(y, duration):
return cmp(self.value, y.value)
elif isinstance(y, (int, float)):
return cmp(self.value, y)
else:
raise DurationComparisonError
def __lt__(self, y):
"""Compare two duration objects via < (Python 3)"""
if isinstance(y, duration):
return self.value < y.value
elif isinstance(y, (int, float)):
return self.value < y
else:
raise DurationComparisonError
def __le__(self, y):
"""Compare two duration objects via <= (Python 3)"""
if isinstance(y, duration):
return self.value <= y.value
elif isinstance(y, (int, float)):
return self.value <= y
else:
raise DurationComparisonError
def __gt__(self, y):
"""Compare two duration objects via > (Python 3)"""
if isinstance(y, duration):
return self.value > y.value
elif isinstance(y, (int, float)):
return self.value > y
else:
raise DurationComparisonError
def __ge__(self, y):
"""Compare two duration objects via >= (Python 3)"""
if isinstance(y, duration):
return self.value >= y.value
elif isinstance(y, (int, float)):
return self.value >= y
else:
raise DurationComparisonError
def __eq__(self, y):
"""Compare two duration objects via == (Python 3)"""
if isinstance(y, duration):
return self.value == y.value
elif isinstance(y, (int, float)):
return self.value == y
else:
raise DurationComparisonError
def __add__(self, y):
"""Add two durations or a duration and an int or float"""
if isinstance(y, duration):
return duration(self.value + y.value)
elif isinstance(y, (int, float)):
return duration(self.value + y)
elif isinstance(y, timestamp):
return timestamp(self.value + y.value)
else:
raise DurationAddError
def __sub__(self, y):
"""Subtract two durations or a duration and an int or float"""
if isinstance(y, duration):
return duration(self.value - y.value)
elif isinstance(y, (int, float)):
return duration(self.value - y)
else:
raise DurationSubtractError
def __mul__(self, y):
"""Multiply a duration by an int or float"""
if isinstance(y, (int, float)):
return duration(self.value * y)
else:
raise DurationMultiplyError
def __div__(self, y):
"""Divide a duration by an int or float"""
if isinstance(y, (int, float)):
return duration(self.value / y)
else:
raise DurationDivideError
def __truediv__(self, y):
"""Divide a duration by an int or float"""
if isinstance(y, (int, float)):
return duration(self.value / y)
else:
raise DurationDivideError
def __floordiv__(self, y):
"""Divide a duration by an int or float"""
if isinstance(y, (int, float)):
return duration(self.value // y)
else:
raise DurationDivideError
class _bdict(dict):
"""Enhanced dictionary used to store the formats"""
def __missing__(self, key):
if key == None:
key = 'base'
return self[key] if key in self else key
class timestamp(object):
"""Represents a specific point in time
``value`` can be:
* int/float in epoch seconds in UTC or a string that looks like
one: sets the value directly
* Anything else is passed to the ``time`` function along with the
values of the ``tz``, ``fmt``, and ``ntp`` arguments
Internal storage is float epoch seconds in UTC and accessible via
the ``value`` property.
Timestamp objects can be compared via ``<``, ``>``, ``<=``, ``>=``,
``==``, and ``!=`` with each other.
Timestamp objects support various arithmetic operations via ``+``
and ``-``.
+----------+----------------------+---------------+
| Operator | Other type | Returned type |
+==========+======================+===============+
| ``+`` | int, float, duration | timestamp |
+----------+----------------------+---------------+
| ``-`` | int, float, duration | timestamp |
+ +----------------------+---------------+
| | timestamp | duration |
+----------+----------------------+---------------+
Arithmetic operations with a type not listed in the above table
raises one of ``TimestampAddError``, ``TimestampDivideError``,
``TimestampMultipyError``, or ``TimestampSubtractError``.
"""
formats = _bdict(
base='%Y-%m-%d %H:%M:%S',
basetz='%Y-%m-%d %H:%M:%S %Z',
HH='%H',
HH_MM='%H:%M',
HH_MM_SS='%H:%M:%S',
HHMM='%H%M',
HHMMSS='%H%M%S',
MM='%M',
SS='%S',
abbr_date='%a, %b %d, %Y',
abbr_month='%b',
abbr_weekday='%a',
ampm='%p',
ccyy='%Y',
ccyymm='%Y%m',
ccyymmdd='%Y%m%d',
d='%a',
date='%A, %B %d, %Y',
day='%A',
dd='%d',
dd_Mon_yyyy='%d %b %Y',
hh='%I',
hh_MM='%I:%M',
hh_MM_ampm='%I:%M %p',
hh_MM_SS='%I:%M:%S',
hh_MM_SS_ampm='%I:%M:%S %p',
hours='%H',
hours12='%I',
hours24='%H',
iso8601='%Y-%m-%dT%H:%M:%SZ',
julian='%j',
microseconds='%f',
minutes='%M',
mm='%m',
mm_dd_yy='%m/%d/%y',
mmdd='%m%d',
mon='%b',
month='%B',
national='%a %b %d %X %Z %Y',
national_date='%x',
national_time='%X',
rfc2822='%a, %d %b %Y %H:%M:%S %z',
rfc2822_='%a, %d %b %Y %H:%M:%S',
seconds='%S',
tz='%Z',
tz_offset='%z',
week_number_mon='%W',
week_number_sun='%U',
weekday='%A',
year='%Y',
yy='%y',
yymm='%y%m',
yymmdd='%y%m%d',
yyyy='%Y',
yyyy_mm_dd='%Y/%m/%d',
yyyymm='%Y%m',
yyyymmdd='%Y%m%d',
)
def __init__(self, value=None, tz=None, fmt=None, ntp=False):
if isinstance(value, (int, float)):
self.value = float(value)
elif isinstance(value, str) and \
re.search(r'^\d+\.?\d*$', value):
self.value = float(value)
else:
self.value = time(value, tz, fmt, ntp)
self.value = round(self.value, 6)
def __cmp__(self, y):
"""Compare two timestamps"""
if isinstance(y, timestamp):
return cmp(self.value, y.value)
else:
raise TimestampComparisonError
def __lt__(self, y):
"""Compare two timestamps via < (Python 3)"""
if isinstance(y, timestamp):
return self.value < y.value
else:
raise TimestampComparisonError
def __le__(self, y):
"""Compare two timestamps via <= (Python 3)"""
if isinstance(y, timestamp):
return self.value <= y.value
else:
raise TimestampComparisonError
def __gt__(self, y):
"""Compare two timestamps via > (Python 3)"""
if isinstance(y, timestamp):
return self.value > y.value
else:
raise TimestampComparisonError
def __ge__(self, y):
"""Compare two timestamps via >= (Python 3)"""
if isinstance(y, timestamp):
return self.value >= y.value
else:
raise TimestampComparisonError
def __eq__(self, y):
"""Compare two timestamps via == (Python 3)"""
if isinstance(y, timestamp):
return self.value == y.value
else:
raise TimestampComparisonError
def __sub__(self, y):
"""Subtract two timestamps to produce a duration object, or a
duration, int, or float from a timestamp to produce a new
timestamp object"""
if isinstance(y, timestamp):
return duration(abs(self.value - y.value))
elif isinstance(y, duration):
return timestamp(self.value - y.value)
elif isinstance(y, (int, float)):
return timestamp(self.value - y)
else:
raise TimestampSubtractError
def __add__(self, y):
"""Add a duration, int, or float to a timestamp to produce a
new timestamp object"""
if isinstance(y, duration):
return timestamp(self.value + y.value)
elif isinstance(y, (int, float)):
return timestamp(self.value + y)
else:
raise TimestampAddError
def __mul__(self, y):
"""Cannot multiply a timestamp"""
raise TimestampMultiplyError
def __div__(self, y):
"""Cannot divide a timestamp"""
raise TimestampDivideError
def __truediv__(self, y):
"""Cannot divide a timestamp"""
raise TimestampDivideError
def __floordiv__(self, y):
"""Cannot divide a timestamp"""
raise TimestampDivideError
def str(self, tz=None, fmt=None):
"""Returns the timestamp as a string in the local or given
timezone and the 'basetz' or given format"""
d = datetime.datetime.fromtimestamp(self.value)
d = timezone().pytz.localize(d)
if fmt == 'iso8601':
tz = 'UTC'
if tz != pytz.utc:
tz = timezone(tz).pytz
d = tz.normalize(d.astimezone(tz))
if fmt == None:
fmt = 'basetz'
if fmt == 'Month_Nth':
r = d.strftime('%%B %s' % _nth(d.strftime('%d')))
elif fmt == 'Month_Nth_YYYY':
r = d.strftime('%%B %s, %%Y' % _nth(d.strftime('%d')))
elif fmt == 'Day_Month_Nth':
r = d.strftime('%%A, %%B %s' % _nth(d.strftime('%d')))
elif fmt == 'Day_Month_Nth_YYYY':
r = d.strftime('%%A, %%B %s, %%Y' % _nth(d.strftime('%d')))
else:
r = d.strftime(self.formats[fmt])
return r
def utc(self, fmt='basetz'):
"""Returns the timestamp as a string in the UTC timezone and
the 'basetz' or given format"""
return self.str('UTC', fmt)
def rfc2822(self, tz=None):
"""Returns the timestamp as a string in the local or given
timezone and the 'rfc2822' format"""
return self.str(tz, 'rfc2822')
def iso8601(self):
"""Returns the timestamp as a string in the UTC timezone
(implied) and the 'iso8601' format"""
return self.str(fmt='iso8601')
def dict(self, tz=[None], fmt=['basetz']):
"""Returns the timestamp as a dictionary with keys as the
given timezones and values as dictionaries with keys as the
given formats (default: 'basetz')"""
if fmt == 'all' or isinstance(fmt, list) and 'all' in fmt:
fmt = list(self.formats.keys())
if not isinstance(tz, list):
tz = [tz]
if not isinstance(fmt, list):
fmt = [fmt]
r = {}
for t in tz:
if t == None:
t = 'localtz'
r[t] = {}
for f in fmt:
if f == None:
f = 'basetz'
r[t][f] = self.str(t if t != 'localtz' else None, f)
return r
def json(self, tz=[None], fmt=['basetz']):
"""Returns the dictionary produced by the ``dict`` method as a
pretty-printed JSON string"""
return _json(self.dict(tz, fmt))
class timezone(object):
"""Represent a timezone
``name`` is stored in the ``original`` property, and resolved to a
timezone name via ``timezone.search``, which is stored in the
``name`` property.
A pytz object is created for the given name and accessible via the
``pytz`` property.
"""
def __init__(self, name=None):
self.original = name
self.name = self.search(name)
if isinstance(self.name, list):
if len(self.name) == 0:
raise TimezoneFailure('No timezone found for "%s"' % name)
else:
raise TimezoneMultiple('Found multiple possible timezones' + \
' for "%s": %s' % (name, ', '.join(self.name)))
self.pytz = pytz.timezone(self.name)
@classmethod
def search(cls, name=None):
"""Resolve timezone given a name
``name`` can be:
* omitted or None: returns name of the local timezone via
tzlocal or UTC
* string matching a timezone name in ``pytz.all_timezones``:
returns the timezone name in proper case
* empty string ('') or wildcard regular expression ('.*'):
returns a list with all timezone names
* any other string: used as a regular expression; multiple or
zero matches returns a list with the matched timezone names
"""
if name == None:
try:
return tzlocal.get_localzone().zone
except:
return 'UTC'
if name in pytz.all_timezones:
return name
name_ = name.lower()
matches = []
for t in pytz.all_timezones:
t_ = t.lower()
if name_ == t_:
return t
if re.search(name, t) or re.search(name_, t_):
matches.append(t)
if len(matches) == 1:
return matches[0]
else:
return matches
# Error classes
class KronError(Exception):
"""Base exception class"""
pass
class DurationAddError(KronError):
pass
class DurationComparisonError(KronError):
pass
class DurationDivideError(KronError):
pass
class DurationMultiplyError(KronError):
pass
class DurationSubtractError(KronError):
pass
class NTPError(KronError):
pass
class TimeEpochError(KronError):
pass
class TimeFormatError(KronError):
pass
class TimeTimezoneError(KronError):
pass
class TimestampAddError(KronError):
pass
class TimestampComparisonError(KronError):
pass
class TimestampMultiplyError(KronError):
pass
class TimestampDivideError(KronError):
pass
class TimestampSubtractError(KronError):
pass
class TimezoneFailure(KronError):
pass
class TimezoneMultiple(KronError):
pass
# Functions
def time(value=None, tz=None, fmt=None, ntp=False):
"""Primitive functional interface for the ``timestamp`` class;
similar to ``time.time()``, except more flexible and consistent;
optionally attempts to use NTP with a fallback to use system time;
can also process a string timestamp; returns float epoch seconds
in UTC
``value`` can be:
* omitted or None: use current date and time now (via system time
if ``ntp`` is False (default) or NTP if ``ntp`` is True); raises
``TimeTimezoneError`` if ``tz`` is specified or
``TimeFormatError`` if ``fmt`` is specified
* string timestamp in the ``base`` format or given by ``fmt`` and
the local timezone or given by ``tz``
"""
if value == None:
# now
if tz != None:
raise TimeTimezoneError('defined tz while value is None')
if fmt != None:
raise TimeFormatError('defined fmt while value is None')
if ntp:
try:
r = time_ntp()
except NTPError:
r = time_utc()
else:
r = time_utc()
else:
# process as a string timestamp
d = datetime.datetime.strptime(value, timestamp.formats[fmt])
if fmt == 'iso8601':
tz = 'UTC'
r = time_utc(d, tz)
return r
def time_ntp(server='us.pool.ntp.org'):
"""Similar to ``time_utc``, except uses NTP
``server`` can be any Internet or other network-based NTP server.
``time_ntp`` raises ``NTPError`` if it fails to retrieve the time
from the server.
"""
c = ntplib.NTPClient()
try:
res = c.request(server, version=3)
except:
raise NTPError
# convert from seconds since 1900 to seconds since 1970
r = res.tx_timestamp - 2208988800
# convert to utc
r = time_utc(r)
return r
def time_utc(epoch=None, tz=None):
"""Similar to ``time.time()``, except always returns float epoch
seconds in UTC
``epoch`` argument can be one of the following; otherwise it
raises ``TimeEpochError``.
* omitted or None: use current date and time now (via system time)
* int/float: epoch seconds in UTC
* datetime.datetime object
``tz`` is passed to ``timezone()``.
"""
if epoch == None:
d = datetime.datetime.now()
elif isinstance(epoch, (int, float)):
d = datetime.datetime.fromtimestamp(epoch)
elif isinstance(epoch, datetime.datetime):
d = epoch
else:
raise TimeEpochError('epoch must be None, int, float, or datetime')
d = timezone(tz).pytz.localize(d)
r = calendar.timegm(d.utctimetuple())
r += d.microsecond / float(10**6)
return r
def cli(argv=None):
"""Backend function for command line interface"""
p = argparse.ArgumentParser()
p.add_argument('-V', '--version', action='store_true', \
help='print version and exit')
p.add_argument('-T', metavar='TIMEZONE', action='store', \
help='input timezone; default: local timezone')
p.add_argument('-F', metavar='FORMAT', action='store', \
help='input format; default: "base" ("%%Y-%%m-%%d %%H:%%M:%%S")')
p.add_argument('-t', metavar='TIMEZONE', action='append', default=[], \
help='output timezone; default: local timezone')
p.add_argument('-f', metavar='FORMAT', action='append', default=[], \
help='output format; default: "basetz" ("%%Y-%%m-%%d ' + \
'%%H:%%M:%%S %%Z"); try "all" for a demonstration')
p.add_argument('-s', metavar='TIMEZONE', action='store', \
help='search timezones')
p.add_argument('args', metavar='ARG', action='store', nargs='*', \
help='one or more timestamps; int/float epoch seconds,' + \
' string in the base format or the format specified by -F;' + \
' default: now')
a = p.parse_args(argv)
if a.version:
return __version__
if a.s != None:
r = timezone.search(a.s)
if not isinstance(r, list):
r = [r]
return '\n'.join(r)
for i in (a.args, a.t, a.f):
if i == None:
i = []
if i == []:
i.append(None)
if len(a.args) + len(a.t) + len(a.f) == 3 and not 'all' in a.f:
return timestamp(a.args[0], a.T, a.F).str(a.t[0], a.f[0])
r = {}
for i in a.args:
r[i if i != None else 'now'] = timestamp(i, a.T, a.F).dict(a.t, a.f)
return _json(r)
def main():
"""Frontend function for command line interface"""
import sys
print(cli(sys.argv[1:]))
def _json(obj):
"""Drop-in replacement for json.dumps() with pretty-printing"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
def _nth(n):
"""Convert an integer to a string with ordinal letters
For example, `_nth(1)` returns "1st", `_nth(2)` returns "2nd", etc.
"""
t = 'th'
a = {'11': t, '12': t, '13': t, '1': 'st', '2': 'nd', '3': 'rd'}
n = str(int(n))
return n + a.get(n[-2:], a.get(n[-1], t))
# Main
if __name__ == '__main__':
main()