Skip to content

Instantly share code, notes, and snippets.

@bedilbek
Last active March 21, 2025 08:50
Show Gist options
  • Select an option

  • Save bedilbek/acdca728461a75e0f49bfdd21f7e3537 to your computer and use it in GitHub Desktop.

Select an option

Save bedilbek/acdca728461a75e0f49bfdd21f7e3537 to your computer and use it in GitHub Desktop.
Datetime string to epoch and vice versa
#!/usr/bin/python3
"""
Examples:
------------------------------------------------------
echo "1742546018015123" | ctte.py --reverse --us
2025-03-21T08:33:38.015Z
2025-03-21T08:33:38.015123Z
------------------------------------------------------
echo "1742546018015" | ctte.py --reverse --ms
2025-03-21T08:33:38.000Z
2025-03-21T08:33:38.000015Z
------------------------------------------------------
echo "1742546018015" | ctte.py --reverse
--ms is implied by default
2025-03-21T08:33:38.000Z
2025-03-21T08:33:38.000015Z
------------------------------------------------------
echo "2025-03-21T08:33:38.015Z" | ctte.py
1742546018.015
1742546018015
1742546018015000
------------------------------------------------------
"""
import sys
from datetime import datetime
import argparse
def main(args):
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f%z"
times = "".join(sys.stdin.readlines())
for t in times.split('\n'):
try:
if t:
if not args.reverse:
dt = datetime.strptime(t, TIME_FORMAT)
print(dt.timestamp())
print(int(dt.timestamp()*1000))
print(int(dt.timestamp()*1000*1000))
else:
t = int(t)
if args.ms:
m = t % 1000
t = t // 1000
if args.us:
m = t % 1000000
t = t // 1000000
final_t = datetime.utcfromtimestamp(t).replace(microsecond=m).replace(tzinfo=None)
print(final_t.isoformat(timespec="milliseconds") + "Z")
print(final_t.isoformat(timespec="microseconds") + "Z")
except Exception as e:
if not args.reverse:
print(f"Wrong format '{t}'. Format must be: {TIME_FORMAT}")
else:
print(f"Wrong format '{t}'. It should be unix epoch in milliseconds if --ms, otherwise unix epoch in microseconds if --us is provided")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--reverse", action="store_true")
parser.add_argument("--ms", action="store_true")
parser.add_argument("--us", action="store_true")
args = parser.parse_args()
if args.reverse is True and args.ms is True and args.us is True:
print("When --reverse is used, only one of --ms or --us is required, they are mutually exclusive")
exit(1)
if args.reverse is True and args.ms is False and args.us is False:
print("\n--ms is implied by default\n")
args.ms = True
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment