Created
November 10, 2024 21:17
-
-
Save nobrowser/5c55644cb740549498f3796ded61afed to your computer and use it in GitHub Desktop.
convert time between timezones using modern python
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 | |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter | |
import time | |
import datetime as DT | |
import zoneinfo as ZI | |
import sys | |
TZFILE = "/etc/timezone" | |
def get_local_timezone(): | |
with open(TZFILE) as h: | |
return h.read().strip() | |
GMFMT = "{0}-{1:#02}-{2:#02} {3:#02}:{4:#02}" | |
def gmtime_as_str(): | |
return GMFMT.format(*time.gmtime()) | |
def main(): | |
ap = ArgumentParser( | |
prog="tzcvt", | |
description="convert date and time between timezones", | |
formatter_class=ArgumentDefaultsHelpFormatter, | |
) | |
ap.add_argument( | |
"-i", "--input_format", | |
default="%Y-%m-%d %H:%M", | |
metavar="FORMAT", | |
help="format for strptime(3) to parse time argument", | |
) | |
ap.add_argument( | |
"-o", "--output_format", | |
default="%Y-%m-%d %H:%M:%S %z", | |
metavar="FORMAT", | |
help="format for strftime(3) to print the result", | |
) | |
ap.add_argument( | |
"-t", "--timezone", | |
default="UTC", | |
metavar="TZ", | |
help="name of timezone to interpret time argument", | |
) | |
ap.add_argument( | |
"-l", "--local_timezone", | |
default=get_local_timezone(), | |
metavar="TZ", | |
help="name of timezone to reinterpret and print result", | |
) | |
ap.add_argument( | |
"time", | |
nargs='?', | |
default=gmtime_as_str(), | |
help="input time", | |
) | |
opts = ap.parse_args() | |
in_datetime = DT.datetime.strptime(opts.time, opts.input_format) | |
in_date, in_time = in_datetime.date(), in_datetime.time() | |
in_tz = ZI.ZoneInfo(opts.timezone) | |
in_combined = DT.datetime.combine(in_date, in_time, in_tz) | |
out_datetime = in_combined.astimezone(ZI.ZoneInfo(opts.local_timezone)) | |
sys.stdout.write(out_datetime.strftime(opts.output_format)) | |
sys.stdout.write("\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment