-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse-date-time
More file actions
executable file
·52 lines (39 loc) · 1.28 KB
/
parse-date-time
File metadata and controls
executable file
·52 lines (39 loc) · 1.28 KB
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
#!/usr/bin/env -S uv --quiet run --no-project --script --
# https://peps.python.org/pep-0723/
# https://github.com/astral-sh/uv
# /// script
# requires-python = ">=3.14,<4"
# dependencies = [
# "parsedatetime >=2.6",
# "tzlocal >=5.2",
# ]
# ///
import sys, datetime
import parsedatetime
import tzlocal
def main():
input_str = sys.argv[1]
local_timezone = tzlocal.get_localzone()
# Setting the reference time to last year this date and time.
# If the year is not specified, the resulting date will be in the past.
#TODO This breaks day of week based parsing.
reference_time = datetime.datetime.now().replace(tzinfo=local_timezone)
reference_time = reference_time.replace(year=(reference_time.year - 1))
calendar = parsedatetime.Calendar()
result, retcode = calendar.parseDT(input_str, sourceTime=reference_time)
if retcode == 0 or not result:
print(input_str)
return
if result.tzinfo is None:
result = result.replace(tzinfo=local_timezone)
if retcode == 1: # parsed as C{date}
print(f"{result:%F}")
elif retcode == 2: # parsed as C{time}
print(f"{result:%T}")
elif retcode == 3: # parsed as C{datetime}
print(f"{result:%FT%T%:z}")
else:
print("(unexpected result from parsedatetime)")
#TODO Implement "? week(s) from ???"
if __name__ == '__main__':
sys.exit(main())