Skip to content

Instantly share code, notes, and snippets.

@philpennock
Created July 15, 2020 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philpennock/fe371c52ac778b908aef360ec8030dfe to your computer and use it in GitHub Desktop.
Save philpennock/fe371c52ac778b908aef360ec8030dfe to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
time_render: render time as given on cmdline
Convert epoch time (default) to something human-readable.
Handle obscenely large numbers.
"""
# DNS uses u_int48_t (for TSIG) which is seconds since Unix epoch.
# That means we need to scale up to taking: 281474976710655
__author__ = 'phil.pennock@spodhuis.org (Phil Pennock)'
import argparse
import sys
import time
_DEF_TIMEFMT = '%Y-%m-%dT%H:%M:%S %z (%c %Z)'
class Error(Exception):
"""Base class for exceptions from time_render."""
pass
class Time(object):
def __init__(self, spec, options):
try:
self.unix_epoch = int(spec)
except ValueError:
self.unix_epoch = float(spec)
if options.nanoseconds:
self.unix_epoch = float(self.unix_epoch) / 1000000000
elif options.microseconds:
self.unix_epoch = float(self.unix_epoch) / 1000000
elif options.milliseconds:
self.unix_epoch = float(self.unix_epoch) / 1000
self.fmt_spec = options.format
def _as_time(self):
return time.localtime(self.unix_epoch)
def Render(self, out):
print(time.strftime(self.fmt_spec, self._as_time()), file=out)
def _main(args, argv0):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f', '--format',
default=_DEF_TIMEFMT,
help='Specify output format')
parser.add_argument('--ms',
dest='milliseconds', default=False, action='store_true',
help='times are in milliseconds')
parser.add_argument('--us',
dest='microseconds', default=False, action='store_true',
help='times are in microseconds')
parser.add_argument('--ns',
dest='nanoseconds', default=False, action='store_true',
help='times are in nanoseconds')
parser.add_argument('input_times', nargs='+',
help='timestamps to convert')
options = parser.parse_args(args=args)
for t in options.input_times:
tl = t.lower()
if tl == 'ns':
options.milliseconds = False
options.microseconds = False
options.nanoseconds = True
continue
elif tl == 'us' or tl == 'μs':
options.milliseconds = False
options.microseconds = True
options.nanoseconds = False
continue
elif tl == 'ms':
options.milliseconds = True
options.microseconds = False
options.nanoseconds = False
continue
elif tl == 's' or tl == 'seconds':
options.milliseconds = False
options.microseconds = False
options.nanoseconds = False
continue
Time(t, options).Render(sys.stdout)
if __name__ == '__main__':
argv0 = sys.argv[0].rsplit('/')[-1]
rv = _main(sys.argv[1:], argv0=argv0)
sys.exit(rv)
# vim: set ft=python sw=2 expandtab :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment