Files

64 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
# epoch - convert between epoch seconds and human dates, both ways
# Usage: epoch [VALUE] [--now] [--ms] [--utc] [--format FMT]
# A numeric VALUE is read as epoch seconds (-> date); a date string (-> epoch).
# With no VALUE, prints the current epoch.
import argparse, sys, time
from datetime import datetime, timezone
def selftest():
assert datetime.fromtimestamp(0, tz=timezone.utc).strftime("%Y-%m-%d") == "1970-01-01"
assert int(datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp()) == 1767225600
assert int(datetime.fromtimestamp(1767225600, tz=timezone.utc).timestamp()) == 1767225600
print("epoch selftest: ok (0 -> 1970-01-01 UTC, 2026-01-01 round-trip)")
return 0
def parse_date(s, fmt):
for f in (fmt, "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(s, f)
except ValueError:
continue
raise ValueError(f"cannot parse date {s!r}")
def main():
p = argparse.ArgumentParser(prog="epoch",
description="Convert between epoch seconds and human dates, both ways.")
p.add_argument("value", nargs="?", help="epoch seconds, or a date like 2026-01-01[ 12:00:00]")
p.add_argument("--now", action="store_true", help="print the current epoch (and date)")
p.add_argument("--ms", action="store_true", help="work in milliseconds instead of seconds")
p.add_argument("--utc", action="store_true", help="use UTC instead of local time")
p.add_argument("--format", default="%Y-%m-%d %H:%M:%S %Z", help="date output format")
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
a = p.parse_args()
if a.selftest:
return selftest()
tz = timezone.utc if a.utc else None
scale = 1000 if a.ms else 1
if a.now or a.value is None:
now = time.time()
dt = datetime.fromtimestamp(now, tz=tz)
print(f"{int(now * scale)} ({dt.strftime(a.format)})")
return 0
v = a.value.strip()
try:
num = float(v)
dt = datetime.fromtimestamp(num / scale, tz=tz)
print(dt.strftime(a.format))
return 0
except (ValueError, OverflowError, OSError):
pass
try:
dt = parse_date(v, a.format if "%" in a.format and a.format != "%Y-%m-%d %H:%M:%S %Z" else "%Y-%m-%d %H:%M:%S")
except ValueError as e:
print(f"epoch: {e}", file=sys.stderr); return 2
if a.utc:
dt = dt.replace(tzinfo=timezone.utc)
else:
dt = dt.astimezone()
print(int(dt.timestamp() * scale))
return 0
if __name__ == "__main__":
sys.exit(main())