-
-
Save qingfeng/5dd5f4961ff2535353a89b0d2fc06b0b to your computer and use it in GitHub Desktop.
一个方便计算时间在各个时区的脚本
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
#!/usr/bin/env python3 | |
""" | |
This script converts a given time (with optional date and timezone) into the equivalent time across multiple timezones. | |
Usage: | |
./wt "2024-02-23 12:00" "UTC" # Converts the specified UTC time to different timezones. | |
./wt "12:00" "Asia/Tokyo" # Converts the specified Tokyo time to different timezones. | |
./wt "2024-02-23" # Converts the start of the specified day in local timezone to different timezones. | |
./wt "12:00" # Converts the specified local time (no date) to different timezones. | |
./wt # Converts the current local time to different timezones. | |
Note: | |
If the date is not specified, the current date is used. | |
If the timezone is not specified, the local timezone is assumed for the input time. | |
""" | |
from dateutil import parser | |
from datetime import datetime | |
import sys | |
from zoneinfo import ZoneInfo | |
# 定义默认时间为当前日期的午夜(00:00:00),确保秒数为0 | |
default_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) | |
# List of timezones to convert the given time into. | |
time_zones = [ | |
'Asia/Tokyo', 'UTC', 'Asia/Singapore', 'Asia/Bangkok', | |
'Europe/London', 'America/Los_Angeles', 'America/Sao_Paulo' | |
] | |
# 检查是否提供了时间参数 | |
if len(sys.argv) > 1: | |
input_param = sys.argv[1] | |
# 使用dateutil解析时间参数 | |
local_time = parser.parse(input_param, default=default_time) | |
else: | |
# 没有提供时间参数,使用当前时间 | |
local_time = datetime.now() | |
# 动态获取本地时区 | |
local_tz = datetime.now().astimezone().tzinfo | |
# 设置为用户指定的时区或默认使用当前本地时区 | |
if len(sys.argv) > 2: | |
input_timezone_str = sys.argv[2] | |
input_timezone = ZoneInfo(input_timezone_str) | |
else: | |
input_timezone = local_tz | |
# 确保local_time带有正确的时区信息 | |
if not local_time.tzinfo: | |
local_time = local_time.replace(tzinfo=input_timezone) | |
# 计算最长的时区名称长度 | |
max_tz_length = max(len(tz) for tz in time_zones) | |
# 转换并打印各个时区的时间 | |
for tz_str in time_zones: | |
tz = ZoneInfo(tz_str) | |
target_time = local_time.astimezone(tz) | |
# 使用字符串格式化来对齐输出 | |
print(f"{tz_str:{max_tz_length}}: {target_time.strftime('%Y-%m-%d %H:%M:%S %Z%z')}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment