Last active
March 21, 2024 02:19
-
-
Save shinkou/4ad5f47c65f113912d9882a43ddfab3c to your computer and use it in GitHub Desktop.
Local/Remote Time Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# vim: fileencoding=utf-8 ff=unix | |
from datetime import datetime | |
from zoneinfo import ZoneInfo | |
import argparse, os, time | |
def get_args(): | |
parser = argparse.ArgumentParser( | |
description='Local/Remote Time Converter' | |
) | |
parser.add_argument( | |
'--no-color' | |
, action='store_true' | |
, default='TERM' not in os.environ | |
or 'color' not in os.environ['TERM'].lower() | |
, help='disable color display' | |
) | |
parser.add_argument( | |
'-l', '--local-timezone' | |
, type=str | |
, metavar='TIMEZONE' | |
, default=os.environ['TZ'] if 'TZ' in os.environ else 'UTC' | |
, help='local timezone name (default: env TZ value or "UTC")' | |
) | |
parser.add_argument( | |
'-r', '--remote-timezone' | |
, type=ZoneInfo | |
, metavar='TIMEZONE' | |
, default=os.environ['TZ'] if 'TZ' in os.environ else 'UTC' | |
, help='remote timezone name (default: env TZ value or "UTC")' | |
) | |
parser.add_argument( | |
'datetimes' | |
, type=datetime.fromisoformat | |
, metavar='DATETIME' | |
, nargs='*' | |
, help='date/time in ISO format (default: now)' | |
) | |
return parser.parse_args() | |
def ansi(s, fg=7, bg=0, fx=0): | |
return '\x1b[%d;3%d;4%dm%s\x1b[0m' % (fx, fg, bg, s) | |
def ansi_output(dt, remotedt): | |
print( | |
ansi(" Local Time ", bg=1) | |
+ ansi(f" {dt} ", fg=1) | |
) | |
print( | |
ansi(" Remote Time ", bg=2) | |
+ ansi(f" {remotedt} ", fg=2) | |
) | |
print( | |
ansi(" Timezone ", bg=3) | |
+ ansi(f" {remotedt.tzname()} ", fg=3) | |
) | |
print( | |
ansi(" DST Adjustment ", bg=4) | |
+ ansi(f" {remotedt.dst()} ", fg=4) | |
) | |
def normal_output(dt, remotedt): | |
print(f" Local Time: {dt}") | |
print(f" Remote Time: {remotedt}") | |
print(f" Timezone: {remotedt.tzname()}") | |
print(f"DST Adjustment: {remotedt.dst()}") | |
def conv_datetime(dt: datetime, tzinfo: ZoneInfo, fn_render): | |
'''Convert and display local time to remote time''' | |
remotedt = dt.astimezone(tzinfo) | |
fn_render(dt, remotedt) | |
def main(): | |
args = get_args() | |
os.environ['TZ'] = args.local_timezone | |
time.tzset() | |
fn_output = normal_output if args.no_color else ansi_output | |
if args.datetimes: | |
for dt in args.datetimes: | |
conv_datetime(dt, args.remote_timezone, fn_output) | |
else: | |
conv_datetime(datetime.now(), args.remote_timezone, fn_output) | |
if '__main__' == __name__: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment