Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active August 31, 2026 10:55
Show Gist options
  • Select an option

  • Save qianlifeng/31363d95905325e9969d93d999e94b07 to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/31363d95905325e9969d93d999e94b07 to your computer and use it in GitHub Desktop.
Wox.Plugin.Script.Timestamp
#!/usr/bin/env python3
# {
# "Id": "c3e8a1d4-7b2f-4f19-9e6a-2d5c8b1a4f70",
# "Name": "i18n:plugin.name",
# "Author": "qianlifeng",
# "Version": "1.0.0",
# "MinWoxVersion": "2.0.0",
# "Description": "i18n:plugin.description",
# "Icon": "emoji:🕗",
# "TriggerKeywords": ["tt"],
# "SupportedOS": ["windows", "linux", "darwin"],
# "I18n": {
# "en_US": {
# "plugin.name": "Timestamp",
# "plugin.description": "Convert between Unix timestamps and datetime strings",
# "label.unix": "Unix timestamp",
# "label.unix_ms": "Unix timestamp (ms)",
# "label.local": "Local time",
# "label.utc": "UTC time",
# "label.iso": "ISO 8601",
# "hint.empty": "Enter a timestamp or datetime to convert",
# "hint.invalid": "Unable to parse this value",
# "hint.invalid.subtitle": "Use a Unix timestamp or a datetime such as 2009-05-01 14:57:32",
# "action.copy": "Copy"
# },
# "zh_CN": {
# "plugin.name": "时间戳",
# "plugin.description": "在 Unix 时间戳和日期时间之间互转",
# "label.unix": "Unix 时间戳",
# "label.unix_ms": "Unix 时间戳(毫秒)",
# "label.utc": "UTC 时间",
# "label.local": "本地时间",
# "label.iso": "ISO 8601",
# "hint.empty": "输入时间戳或日期时间进行转换",
# "hint.invalid": "无法解析这个值",
# "hint.invalid.subtitle": "请输入 Unix 时间戳或日期,例如 2009-05-01 14:57:32",
# "action.copy": "复制"
# }
# }
# }
"""
Wox Timestamp script plugin.
Port of Wox.Plugin.Timestamp (http://www.wox.one/plugin/40):
- tt current Unix timestamp and local time
- tt 1241161052 timestamp -> datetime
- tt 2009-05-01 14:57:32 datetime -> timestamp
"""
from __future__ import annotations
import datetime
import json
import locale
import os
import re
import sys
from typing import Any, List, Optional, Tuple, TypedDict
class WoxPluginBase:
"""Wox plugin base class for script plugins. Do not modify this class."""
class Preview(TypedDict, total=False):
"""Type hint for preview content in a result."""
preview_type: str # "markdown", "text"
preview_data: str
preview_properties: dict[str, str]
class ActionItem(TypedDict, total=False):
"""Type hint for an action in a result."""
id: str
name: str
icon: str
text: str
url: str
path: str
message: str
data: dict[str, str]
class TailItem(TypedDict, total=False):
"""Type hint for a tail in a result."""
id: str
type: str # "text" or "image"
text: str
image: str
contextData: dict[str, str]
class QueryResult(TypedDict, total=False):
"""Type hint for a query result item."""
title: str
subtitle: str
icon: str
preview: WoxPluginBase.Preview
tails: List[WoxPluginBase.TailItem]
score: int
actions: List[WoxPluginBase.ActionItem]
class ActionResult(TypedDict, total=False):
"""Type hint for action method return value."""
action: str
message: str
def __init__(self):
self.log_file_path = __file__ + ".log"
def log(self, message: str) -> None:
"""Log message to log file for debugging."""
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = f"[{ts}] {message}"
if self.is_invoke_from_wox():
with open(self.log_file_path, "a", encoding="utf-8") as f:
f.write(f"{message}\n")
else:
print(f"LOG: {message}")
def is_invoke_from_wox(self) -> bool:
"""Check if the script is invoked from Wox."""
return "WOX_PLUGIN_ID" in os.environ
def _build_response(self, result: Any, request_id: Any) -> dict:
"""Build a successful JSON-RPC 2.0 response."""
return {"jsonrpc": "2.0", "result": result, "id": request_id}
def _build_error_response(
self, code: int, message: str, data: Any = None, request_id: Any = None
) -> dict:
"""Build a JSON-RPC 2.0 error response."""
error = {"code": code, "message": message}
if data is not None:
error["data"] = data
return {"jsonrpc": "2.0", "error": error, "id": request_id}
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
"""Process user queries and return results."""
return []
def action(self, action_id: str, data: Any) -> None:
"""Handle custom actions. Built-in actions are handled by Wox."""
return None
def handle_query(self, params, request_id):
"""Internal method to handle query requests."""
search = params.get("search", "")
trigger_keyword = params.get("trigger_keyword", "")
command = params.get("command", "")
raw_query = params.get("raw_query", "")
results = self.query(raw_query, trigger_keyword, command, search)
return self._build_response({"items": results}, request_id)
def handle_action(self, params, request_id):
"""Internal method to handle action requests."""
action_id = params.get("id", "")
action_data = params.get("data", "")
self.action(action_id, action_data)
return self._build_response({}, request_id)
def run(self):
"""Main entry point for the script plugin."""
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
if self.is_invoke_from_wox():
try:
stdin_text = sys.stdin.read()
except Exception:
return 1
else:
print("Manual mode - please enter query:")
query_input = input()
stdin_text = (
'{"jsonrpc": "2.0", "method": "query", "params": {"search": "'
+ query_input
+ '"}, "id": 1}'
)
try:
request = json.loads(stdin_text)
except json.JSONDecodeError as e:
print(
json.dumps(
self._build_error_response(-32700, "Parse error", str(e), None),
ensure_ascii=False,
)
)
return 1
if request.get("jsonrpc") != "2.0":
print(
json.dumps(
self._build_error_response(
-32600, "Invalid Request", None, request.get("id")
),
ensure_ascii=False,
)
)
return 1
method = request.get("method")
params = request.get("params", {})
request_id = request.get("id")
if method == "query":
response = self.handle_query(params, request_id)
elif method == "action":
response = self.handle_action(params, request_id)
else:
response = self._build_error_response(
-32601,
"Method not found",
f"Method '{method}' not supported",
request_id,
)
print(json.dumps(response, ensure_ascii=False))
return 0
TIMESTAMP_RE = re.compile(r"^-?\d+(?:\.\d+)?$")
DATE_FORMATS = (
"%Y-%m-%d %H:%M:%S",
"%Y/%m/%d %H:%M:%S",
"%Y.%m.%d %H:%M:%S",
"%Y-%m-%d-%H-%M-%S",
"%Y-%m-%d %H:%M:%S.%f",
"%Y/%m/%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M",
"%Y/%m/%d %H:%M",
"%Y-%m-%d",
"%Y/%m/%d",
"%Y.%m.%d",
"%Y年%m月%d日 %H:%M:%S",
"%Y年%m月%d日 %H:%M",
"%Y年%m月%d日",
)
class TimestampPlugin(WoxPluginBase):
ICON = "emoji:🕗"
COPY_ICON = "emoji:📋"
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
text = self._query_text(command, search)
if text.lower() in ("", "now"):
return self._current_results()
parsed = self._parse_input(text)
if parsed is None:
return [
{
"title": "i18n:hint.invalid",
"subtitle": "i18n:hint.invalid.subtitle",
"icon": self.ICON,
"score": 100,
}
]
moment, source = parsed
if source == "timestamp":
return self._timestamp_results(moment)
return self._datetime_results(moment)
def _query_text(self, command: str, search: str) -> str:
parts = [part.strip() for part in (command, search) if part and part.strip()]
return " ".join(parts).strip()
def _parse_input(
self, text: str
) -> Optional[Tuple[datetime.datetime, str]]:
normalized = text.strip().replace(":", ":").replace(",", "").replace("_", "")
timestamp = self._parse_timestamp(normalized)
if timestamp is not None:
return timestamp, "timestamp"
parsed = self._parse_datetime(normalized)
if parsed is not None:
return parsed, "datetime"
return None
def _parse_timestamp(self, text: str) -> Optional[datetime.datetime]:
if not TIMESTAMP_RE.fullmatch(text):
return None
value = float(text)
magnitude = abs(value)
# 13-digit values are milliseconds; 16-digit values are microseconds.
if magnitude >= 1e14:
seconds = value / 1_000_000
elif magnitude >= 1e11:
seconds = value / 1_000
else:
seconds = value
try:
return datetime.datetime.fromtimestamp(seconds)
except (OSError, OverflowError, ValueError):
return None
def _parse_datetime(self, text: str) -> Optional[datetime.datetime]:
iso_text = text
if iso_text.endswith("Z") and iso_text.count("T") == 1:
iso_text = iso_text[:-1] + "+00:00"
try:
parsed = datetime.datetime.fromisoformat(iso_text)
if parsed.tzinfo is not None:
return parsed.astimezone().replace(tzinfo=None)
return parsed
except ValueError:
pass
for fmt in DATE_FORMATS:
try:
return datetime.datetime.strptime(text, fmt)
except ValueError:
continue
return None
def _current_results(self) -> List[WoxPluginBase.QueryResult]:
now = datetime.datetime.now()
return self._datetime_results(now, include_hint=True)
def _timestamp_results(
self, moment: datetime.datetime
) -> List[WoxPluginBase.QueryResult]:
local_text = self._format_local(moment)
utc_text = self._format_utc(moment)
iso_text = self._format_iso(moment)
relative = self._relative_text(moment)
return [
self._copy_result(local_text, "i18n:label.local", 100, relative),
self._copy_result(utc_text, "i18n:label.utc", 90, relative),
self._copy_result(iso_text, "i18n:label.iso", 80, relative),
]
def _datetime_results(
self, moment: datetime.datetime, include_hint: bool = False
) -> List[WoxPluginBase.QueryResult]:
unix_seconds = str(int(moment.timestamp()))
unix_millis = str(int(moment.timestamp() * 1000))
local_text = self._format_local(moment)
utc_text = self._format_utc(moment)
iso_text = self._format_iso(moment)
relative = self._relative_text(moment)
hint = "i18n:hint.empty" if include_hint else relative
return [
self._copy_result(unix_seconds, "i18n:label.unix", 100, hint),
self._copy_result(unix_millis, "i18n:label.unix_ms", 90, hint),
self._copy_result(local_text, "i18n:label.local", 80, relative),
self._copy_result(utc_text, "i18n:label.utc", 70, relative),
self._copy_result(iso_text, "i18n:label.iso", 60, relative),
]
def _copy_result(
self, value: str, subtitle: str, score: int, tail: str = ""
) -> WoxPluginBase.QueryResult:
result: WoxPluginBase.QueryResult = {
"title": value,
"subtitle": subtitle,
"icon": self.ICON,
"score": score,
"actions": [
{
"name": "i18n:action.copy",
"icon": self.COPY_ICON,
"id": "copy-to-clipboard",
"text": value,
}
],
}
if tail:
result["tails"] = [{"type": "text", "text": tail}]
return result
def _format_local(self, moment: datetime.datetime) -> str:
return moment.strftime("%Y-%m-%d %H:%M:%S")
def _format_utc(self, moment: datetime.datetime) -> str:
return moment.astimezone(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
def _format_iso(self, moment: datetime.datetime) -> str:
return moment.astimezone().isoformat(timespec="seconds")
def _is_chinese(self) -> bool:
candidates = [
os.environ.get("LANG", ""),
os.environ.get("LC_ALL", ""),
]
try:
candidates.append(locale.getlocale()[0] or "")
except ValueError:
pass
return any(
value.lower().startswith("zh") or "chinese" in value.lower()
for value in candidates
if value
)
def _relative_text(self, moment: datetime.datetime) -> str:
delta = datetime.datetime.now() - moment.replace(tzinfo=None)
seconds = int(delta.total_seconds())
future = seconds < 0
seconds = abs(seconds)
chinese = self._is_chinese()
if seconds < 5:
return "刚刚" if chinese else "just now"
if seconds < 60:
return self._relative_label(seconds, "秒", "second", future, chinese)
if seconds < 3600:
return self._relative_label(seconds // 60, "分钟", "minute", future, chinese)
if seconds < 86400:
return self._relative_label(seconds // 3600, "小时", "hour", future, chinese)
return self._relative_label(seconds // 86400, "天", "day", future, chinese)
def _relative_label(
self, amount: int, zh_unit: str, en_unit: str, future: bool, chinese: bool
) -> str:
if chinese:
return f"{amount} {zh_unit}{'后' if future else '前'}"
unit = en_unit if amount == 1 else f"{en_unit}s"
if future:
return f"in {amount} {unit}"
return f"{amount} {unit} ago"
if __name__ == "__main__":
sys.exit(TimestampPlugin().run())
@qianlifeng

Copy link
Copy Markdown
Author
image image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment