-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml_date.py
More file actions
84 lines (65 loc) · 2.57 KB
/
xml_date.py
File metadata and controls
84 lines (65 loc) · 2.57 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from datetime import datetime, timedelta
import re
class DateOffset:
years: int
months: int
days: int
def __init__(self, years: int, months: int, days: int):
self.years = years
self.months = months
self.days = days
@staticmethod
def from_datetime(date: datetime):
now = datetime.now()
years = date.year - now.year
months = date.month - now.month
days = date.day - now.day
return DateOffset(years, months, days)
def _format_diff_numeric(self, num: int, suffix: str) -> str:
if num < 0:
return str(num) + suffix
elif num == 0:
return ""
else:
return "+" + str(num) + suffix
def __add__(self, other):
return DateOffset(self.years + other.years, self.months + other.months, self.days + other.days)
def __sub__(self, other):
return DateOffset(self.years - other.years, self.months - other.months, self.days - other.days)
def __str__(self):
days = self._format_diff_numeric(self.days, "d")
months = self._format_diff_numeric(self.months, "M")
years = self._format_diff_numeric(self.years, "y")
return f"[now{years}{months}{days}]"
class XMLDate:
xml_str: str
date: datetime
def __init__(self, xml_str):
self.xml_str = xml_str
self._parse_date()
@staticmethod
def now():
now = datetime.now()
xml_str = now.strftime('"%Y-%m-%d %H:%M:%S"')
return XMLDate(xml_str)
def _parse_date(self):
datetime_str = self.xml_str.replace('"', '')
if re.fullmatch(r'\d{4}-\d{2}-\d{2}', datetime_str):
self.date = datetime.strptime(datetime_str, "%Y-%m-%d")
elif re.fullmatch(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', datetime_str):
self.date = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
elif re.fullmatch(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d', datetime_str):
self.date = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S.%f")
else:
raise ValueError("Invalid date string: {}".format(datetime_str))
def get_relative_date_str(self, diff: DateOffset = DateOffset(0, 0, 0)) -> str:
rel_diff = DateOffset.from_datetime(self.date) + diff
return str(rel_diff)
def __str__(self):
return self.date.strftime("%Y-%m-%d %H:%M:%S.%f")
def __gt__(self, other):
return self.date > other.date
def __lt__(self, other):
return self.date < other.date
def __eq__(self, other):
return self.date == other.date