-
Notifications
You must be signed in to change notification settings - Fork 0
/
epochguess
executable file
·83 lines (74 loc) · 2.5 KB
/
epochguess
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
import sys
import contextlib
from datetime import datetime
from typing import List
import click
def guess_epochs(line: str, after: int, only_first: bool, use_token: str = " ") -> str:
# first guess epoch seconds, then epoch milliseconds
converted: List[str] = []
has_converted = False
for token in line.split(use_token):
# only meant to convert the first token we found, and we've already done that
if only_first and has_converted:
converted.append(token)
continue
# looks like a epoch timestamp
if token.isdigit() or token.isdecimal():
try:
from_secs = datetime.fromtimestamp(float(token))
if from_secs.year < after:
raise ValueError("doesn't meet after constraint")
converted.append(str(from_secs))
has_converted = True
continue
except ValueError:
try:
from_ms = datetime.fromtimestamp(float(token) / 1000)
if from_ms.year < after:
raise ValueError("doesn't meet after constraint")
converted.append(str(from_ms))
has_converted = True
continue
except ValueError:
pass
# if we didn't already 'continue', add the token to the list
converted.append(token)
return " ".join(converted)
@click.command()
@click.option(
"-a",
"--after",
type=int,
default=2000,
help="Timestamp should be after this year, ignore any others",
)
@click.option(
"--first/--not-first",
is_flag=True,
default=True,
help="Only convert the first date found per line",
)
@click.option(
"-d",
"--delimiter",
default=" ",
help="Delimiter to split by when attempting to find possible matches",
)
def main(after: int, first: bool, delimiter: str):
"""
\b
read anything from STDIN
convert any epoch timestamps that looks like a datetime to a date,
convert them to local-readable timestamps
\b
$ printf "%d this is some text" "$(date +"%s")"
1619933459 this is some text
$ printf "%d this is some text" "$(date +"%s")" | epochguess
2021-05-01 22:31:03 this is some text
"""
for line in iter(sys.stdin.readline, ""):
print(guess_epochs(line.strip(), after, first, delimiter))
if __name__ == "__main__":
with contextlib.suppress(KeyboardInterrupt):
main()