jb/scripts/时间戳.py

59 lines
2.3 KiB
Python
Raw Normal View History

2025-06-05 16:40:35 +08:00
from datetime import datetime
import pytz
from typing import List
2025-06-05 16:45:12 +08:00
# 预缓存常用时区
TIMEZONE_CACHE = {
"Asia/Shanghai": pytz.timezone("Asia/Shanghai"),
"UTC": pytz.timezone("UTC"),
"America/New_York": pytz.timezone("America/New_York"),
"Europe/London": pytz.timezone("Europe/London"),
"Australia/Sydney": pytz.timezone("Australia/Sydney")
}
2025-06-05 16:40:35 +08:00
def process(input_strings: List[str]) -> List[str]:
"""处理时间戳和文本的相互转换"""
try:
if len(input_strings) != 3:
return ["错误:输入格式不正确,期望 [mode, input, timezone]"]
mode, input_str, timezone = input_strings
2025-06-05 16:45:12 +08:00
# 从缓存获取时区
tz = TIMEZONE_CACHE.get(timezone)
if not tz:
2025-06-05 16:40:35 +08:00
return ["错误:无效的时区"]
if mode == "timestamp_to_text":
try:
timestamp = int(input_str)
dt = datetime.fromtimestamp(timestamp, tz=tz)
return [dt.strftime("%Y-%m-%d %H:%M:%S %Z")]
except ValueError:
return ["错误:请输入有效的时间戳"]
elif mode == "text_to_timestamp":
try:
2025-06-05 17:19:20 +08:00
# 检查是否以 UTC 结尾
input_str = input_str.strip()
use_utc = input_str.endswith(" UTC")
if use_utc:
input_str = input_str[:-4].strip() # 移除 " UTC"
tz = TIMEZONE_CACHE["UTC"] # 强制使用 UTC 时区
# 尝试解析三种格式
2025-06-05 16:40:35 +08:00
try:
dt = datetime.strptime(input_str, "%Y-%m-%d %H:%M:%S")
except ValueError:
2025-06-05 17:19:20 +08:00
try:
dt = datetime.strptime(input_str, "%Y年%m月%d%H:%M:%S")
except ValueError:
# 解析新格式MMM-DD-YYYY HH:MM:SS AM/PM
dt = datetime.strptime(input_str, "%b-%d-%Y %I:%M:%S %p")
2025-06-05 16:40:35 +08:00
dt = tz.localize(dt)
return [str(int(dt.timestamp()))]
except ValueError:
2025-06-05 17:19:20 +08:00
return ["错误请输入有效的日期格式YYYY-MM-DD HH:MM:SS 或 YYYY年MM月DD日 HH:MM:SS 或 MMM-DD-YYYY HH:MM:SS AM/PM"]
2025-06-05 16:40:35 +08:00
2025-06-05 16:45:12 +08:00
return ["错误:无效的转换模式"]
2025-06-05 16:40:35 +08:00
except Exception as e:
return [f"错误:{str(e)}"]