-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_file.py
More file actions
68 lines (58 loc) · 2.25 KB
/
test_file.py
File metadata and controls
68 lines (58 loc) · 2.25 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
import re
from xml_date import XMLDate, DateOffset
class TestFile:
file_path: str
file_contents: str
dates: list[XMLDate]
def __init__(self, file_path):
self.file_path = file_path
self.file_contents = self._extract_file_contents()
self.dates = self._find_dates()
def _extract_file_contents(self) -> str:
with open(self.file_path, "r") as file:
contents = file.read()
return contents
def _find_dates(self):
# Matches dates and datetime in the following formats
# - "00-00-00"
# - "00-00-00 00:00:00"
# - "00-00-00 00:00:00.0"
dates = re.findall(r'"\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2}:\d{2}(?:\.\d)?)?"', self.file_contents)
dates_formatted = []
for date in dates:
dates_formatted.append(XMLDate(date))
return dates_formatted
def _get_lower_max(self) -> XMLDate:
now = XMLDate.now()
lower_dates = list(filter(lambda x: x < now, self.dates))
if len(lower_dates) == 0:
return now
return max(lower_dates)
def _get_upper_min(self) -> XMLDate:
now = XMLDate.now()
upper_dates = list(filter(lambda x: x > now, self.dates))
if len(upper_dates) == 0:
return now
return min(upper_dates)
def convert(self):
lower_max = self._get_lower_max()
lower_offset = DateOffset(-1, 0, 0) - DateOffset.from_datetime(lower_max.date)
upper_min = self._get_upper_min()
upper_offset = DateOffset(1, 0, 0) - DateOffset.from_datetime(upper_min.date)
now = XMLDate.now()
date_map = {}
for date in self.dates:
if date > now:
diff = date.get_relative_date_str(upper_offset)
date_map[date.xml_str] = '"' + diff + '"'
else:
diff = date.get_relative_date_str(lower_offset)
date_map[date.xml_str] = '"' + diff + '"'
for string in date_map.keys():
self.file_contents = self.file_contents.replace(string, date_map[string])
def save(self, out_path = ""):
if out_path == "":
out_path = self.file_path
with open(out_path, "w") as file:
file.write(self.file_contents)