#!/usr/bin/python # pytz-date.py - print current UTC, zoneinfo and pytz date time # in optional format "+"$1 in zone $# from datetime import datetime from zoneinfo import ZoneInfo from pytz import timezone import pytz import sys import os TZ = "TZ" # env var GMT = "GMT" # ref zones GMTP0 = "GMT+0" GMTM0 = "GMT-0" UTC = "UTC" refs = [ UTC , GMT , GMTP0 , GMTM0 ] FMT = "%c %Z%z" zi_fmt = "%tzoneinfo%t" pytz_fmt = "%tpytz%t%t" dt_fmt = FMT tz = os.getenv( TZ, UTC) # TZ env var else UTC argc = len( sys.argv ) argn = 1 # $1 +fmt optional override if argc > argn and sys.argv[argn][0] == "+": dt_fmt = sys.argv[argn][1:] argn += 1 # $# zone if argc > argn: tz = sys.argv[argn] # zone ref UTC zones = [ UTC ] # add arg if not same as ref if tz not in refs: zones = zones + [ tz ] # print ref and arg with zoneinfo and pytz for z in zones: # TZ=z date +"f" - zoneinfo print( datetime.now( ZoneInfo( z )).strftime( dt_fmt + zi_fmt + z )) # TZ=z date +"f" - pytz print( datetime.now().astimezone( timezone( z )).strftime( dt_fmt + pytz_fmt + z ))