Created
October 8, 2019 20:29
-
-
Save haginara/eb20cb175674d822fee9382018f23445 to your computer and use it in GitHub Desktop.
Converting timetstamp between diffract timezones.
This file contains 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
import time | |
from datetime import datetime, timedelta | |
# pip install pytz is required. | |
from pytz import timezone | |
import pytz | |
import os | |
import sys | |
import argparse | |
__version_info__ = (0, 2, 0) | |
__version__ = ".".join(map(str, __version_info__)) | |
ALIASES = { | |
"KST": "Asia/Seoul" | |
} | |
def timezone_type(tz_string: str): | |
try: | |
tz = timezone(ALIASES.get(tz_string, tz_string)) | |
except pytz.exceptions.UnknownTimeZoneError: | |
raise argparse.ArgumentTypeError(f"Unknown Timezone: {tz_string}") | |
return tz | |
class PrintAndReturnAction(argparse.Action): | |
def __init__(self, | |
option_strings, | |
dest, | |
help=None, | |
metavar=None): | |
super().__init__( | |
option_strings=option_strings, | |
dest=dest, | |
nargs=0, | |
const=True, | |
default=None, | |
required=False, | |
help=help) | |
def __call__(self, parser, namespace, values, option_string=None): | |
for tz in pytz.all_timezones: | |
print(f"{tz}") | |
parser.exit() | |
def get_options(argv: list) -> argparse.Namespace: | |
default_timeformat = "%Y-%m-%d %H:%M:%S" | |
parser = argparse.ArgumentParser(prog="timeconvert") | |
parser.add_argument( | |
"-v", "--version", action="version", version=f"%(prog)s {__version__}" | |
) | |
parser.add_argument("--list-tz", action=PrintAndReturnAction, help="Print all timezones") | |
parser.add_argument("--print-epoch", action='store_true', help="Print epochtime") | |
parser.add_argument( | |
"--format", | |
type=str, | |
default=default_timeformat, | |
help="TimeFormat for timestamp argument, default: %(default)s", | |
) | |
parser.add_argument( | |
"timestamp", | |
type=str, | |
help="Timstamp string transfer to other timezone" | |
) | |
parser.add_argument("origin_tz", type=timezone_type, help="Origin timezone for timestamp, 'now/NOW' is supported") | |
parser.add_argument("target_tz", type=timezone_type, nargs='+', help="Target timezone for timestamp") | |
options, argv = parser.parse_known_args(argv) | |
try: | |
if options.timestamp.upper() == 'NOW': | |
options.timestamp = datetime.now(options.origin_tz) | |
else: | |
dt = datetime.strptime(options.timestamp, options.format) | |
options.timestamp = options.origin_tz.localize(dt) | |
except Exception as e: | |
print(e) | |
raise SystemExit() | |
return options | |
def main(): | |
UTC = timezone("UTC") | |
options = get_options(sys.argv[1:]) | |
print(f"{str(options.origin_tz):<20}: {options.timestamp.strftime(options.format)}") | |
for target in options.target_tz: | |
target_dt = options.timestamp.astimezone(target) | |
print(f"{str(target):<20}: {target_dt.strftime(options.format)}") | |
if options.print_epoch: | |
print(f"{'epoch':<20}: {options.timestamp.astimezone(UTC).timestamp()}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment