Skip to content

Instantly share code, notes, and snippets.

@wh13371
Created March 15, 2017 12:02
Show Gist options
  • Save wh13371/c70991dc72ea6f773fbfb048c29ced76 to your computer and use it in GitHub Desktop.
Save wh13371/c70991dc72ea6f773fbfb048c29ced76 to your computer and use it in GitHub Desktop.
python - epoch tool
#! /usr/bin/env python
import os, argparse, time, datetime, pytz, json
import logging, logging.handlers
from pprint import pprint
"""
usage examples:
>utc.py # current epoch to timestamp for each timezone
>utc.py 1234567890 # epoch to timestamp for each timezone
>utc.py -t "2009-02-13 23:31:30" # timestamp string to epoch for each timezone
>utc.py -r # run forever
>utc.py -rjl # run forever with pretty json output and logging
"""
log = logging.getLogger(__name__)
_log2file = False
_run_delay = 1
DEFAULT_TIMEZONES = {
'Brisbane' : 'Australia/Brisbane',
'London' : 'Europe/London',
'Sao Paulo' : 'America/Sao_Paulo',
'San Francisco' : 'America/Los_Angeles',
'Kiev' : 'Europe/Kiev',
'Canada/Atlantic' : 'Canada/Atlantic',
'Etc/UTC' : 'Etc/UTC',
'Moscow' : 'Europe/Moscow',
'India' : 'Asia/Kolkata',
'Manila' : 'Asia/Manila' }
CUSTOM_TIMEZONES = {}
def parse_cmd_line_args():
parser = argparse.ArgumentParser(usage='%(prog)s [timestamp] [-hdvrtpjlz]', description='python utc epoch tool')
parser.add_argument('epoch', nargs='?', default=time.time(), help='current epoch or use the [epoch] argv provided')
parser.add_argument('-z', '--timezones', action='store', dest='tz', help='"Europe/Berlin, Africa/Johannesburg, America/Chicago"')
parser.add_argument("-t", "--timestamp", action="store", dest='timestamp', help="timestamp string to epoch")
parser.add_argument('-r', '--run', action='store_true', dest='run', default=False, help='run forever')
parser.add_argument('-p', '--print', action='store_true', dest='print_tz', default=False, help='print all timezones')
parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False, help='debug verbose output')
parser.add_argument("-l", "--log", action="store_true", dest='log', default=False, help="log to file")
parser.add_argument("-j", "--json", action="store_true", dest='json', default=False, help="pretty json output")
parser.add_argument('-v', '--version', action='version', version='%(prog)s v.{version}'.format(version=46.58))
args = parser.parse_args()
return args
def logger_config():
log.setLevel(logging.DEBUG)
log_format = logging.Formatter(fmt='%(message)s')
if args.log:
LOG_FILENAME = 'utc_' + str(epoch()) + '_.log'
file_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=1024*1024*20, backupCount=10)
file_handler.setFormatter(log_format)
log.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_format)
log.addHandler(console_handler)
# local epoch
def epoch():
return time.time()
# epoch irrespective of local
def utcnow():
return str(datetime.datetime.utcnow())
# i.e "1234567890" to "2009-02-13 23:31:30" - no tz awareness
def epoch_to_timestamp(epoch):
return datetime.datetime.fromtimestamp(epoch).strftime('%Y-%m-%d %H:%M:%S.%f')
# i.e "1234567890" to "Europe/London : 2009-02-13 23:31:30.000000"
def epoch_to_timestamp_with_timezone(timestamp, timezone):
return datetime.datetime.fromtimestamp(timestamp, pytz.timezone(timezone)).strftime('%Y-%m-%d %H:%M:%S.%f')
# i.e. "2017-03-12 22:19:49" to a datetime object - used by "args.timestamp"
def datetime_from_string(timestamp_str, format='%Y-%m-%d %H:%M:%S'):
return datetime.datetime.strptime(timestamp_str, format)
# datetime to epoch
def datetime_to_epoch(dt):
#return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S").timestamp() # .timestamp() = 3.3+ only
return time.mktime(dt.timetuple())
# print all the "pytz" timezones
def print_all_tz():
for tz in pytz.all_timezones:
log.debug (tz)
def run():
while 1:
d = {}
d_times = {}
t = epoch()
d['@timestamp'] = epoch_to_timestamp(t) # event timestamp
d['epoch'] = str(t) # event epoch
for k, v in sorted(DEFAULT_TIMEZONES.items()):
d_times[k] = (epoch_to_timestamp_with_timezone(t, v))
d['timestamps'] = d_times # add the timestamp(s)/timezone(s) to the dict
if args.json:
j = json.dumps(d, indent=4, sort_keys=True)
log.info(j)
else:
log.info(d)
time.sleep(_run_delay)
if __name__ == '__main__':
args = parse_cmd_line_args() # args parser
logger_config() # setup logging to console/file
if args.tz: # parse/store any custom timezones
tzs = args.tz.split(',')
for v in tzs:
CUSTOM_TIMEZONES[v.strip()] = v.strip()
DEFAULT_TIMEZONES = CUSTOM_TIMEZONES
if args.debug: log.debug(DEFAULT_TIMEZONES)
if args.timestamp: # i.e. "2009-02-13 23:31:30" to "1234567890" - then convert for each timezone
log.info(datetime_from_string(str(args.timestamp))) # print the datetime string
log.info (str(datetime_to_epoch(datetime_from_string(args.timestamp)))) # convert/print epoch
for k, v in sorted(DEFAULT_TIMEZONES.items()): # for each timezone - convert the epoch to a "timestamp" for each timezone
log.info(k + ":" + epoch_to_timestamp_with_timezone(datetime_to_epoch(datetime_from_string(args.timestamp)), v))
if args.epoch: # i.e. "1234567890" to "2009-02-13 23:31:30" - - then convert for each timezone
if not args.timestamp:
print(str(args.epoch))
for k, v in sorted(DEFAULT_TIMEZONES.items()):
print(k + ":" + epoch_to_timestamp_with_timezone(int(args.epoch), v)) # "epoch" (provided or default)
if args.run:
run() # loop forever
if args.print_tz: # useful to view all "pytz" timezones
print_all_tz()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment