source: stamper/stamper/filters.py@ 63:76140cb24ebd

Last change on this file since 63:76140cb24ebd was 63:76140cb24ebd, checked in by Borja Lopez <borja@…>, 3 years ago

Refactored date-based filters to their own module.

Added a new date-based filter to look for stamps N days/weeks/months/years
*after* a given date, for example:

"2017-06-29+4d" == "four days after the 29th june 2017"
"2017-06-29+1m" == "1 month after the 29th june 2017"

and so on.

File size: 6.5 KB
Line 
1
2import re
3from datetime import datetime, date, timedelta
4
5
6class DateFilter(object):
7
8 """
9 Filtering tools for the dates input provided by the user
10 """
11
12 def __init__(self, date_format):
13 self.date_format = date_format
14
15 def days(self, current_date, days, action='-'):
16 """
17 Add/substract the given number of days from the given current_date
18 """
19 delta = timedelta(days=days)
20 if action == '-':
21 new_date = current_date - delta
22 else:
23 new_date = current_date + delta
24 new_date = new_date.replace(hour=0, minute=0, second=0)
25 return new_date
26
27 def days_ago(self, current_date, days):
28 """
29 Return the date N days ago from the current date
30 """
31 return self.days(current_date, days, '-')
32
33 def days_future(self, current_date, days):
34 """
35 Return the date N days in the future from the current date
36 """
37 return self.days(current_date, days, '+')
38
39 def months(self, current_date, months, action='-'):
40 """
41 Add/substract the given number of months from the given current_date
42 """
43 if action == '-':
44 # start travelling in time, back to N months ago
45 for n in range(months):
46 current_date = current_date.replace(day=1) - timedelta(days=1)
47 else:
48 # start travelling in time, forward to N months
49 for n in range(months):
50 current_date = current_date.replace(day=1) + timedelta(days=1)
51
52 # Now use the new year/month values + the current day to set the proper
53 # date
54 new_date = datetime(
55 current_date.year, current_date.month, date.today().day)
56 return new_date
57
58 def months_ago(self, current_date, months):
59 """
60 Return the date N days ago from the current date
61 """
62 return self.months(current_date, months, '-')
63
64 def months_future(self, current_date, months):
65 """
66 Return the date N days in the future from the current date
67 """
68 return self.months(current_date, months, '+')
69
70 def parse_number_filter(self, number_filter, future=False):
71 """
72 If a filter contains a number of days/months/years, try to find
73 out which filter it is exactly to apply it, then calculate the
74 number of days and find
75 """
76 number = None
77 filter_from = None
78
79 if re.search(r'(\d+[dD]{1})', number_filter):
80 number = int(number_filter.lower().replace('d', ''))
81 if future:
82 filtered_date = self.days_future(datetime.today(), number)
83 else:
84 filtered_date = self.days_ago(datetime.today(), number)
85
86 elif re.search(r'(\d+[wW]{1})', number_filter):
87 number = int(number_filter.lower().replace('w', '')) * 7
88 if future:
89 filtered_date = self.days_future(datetime.today(), number)
90 else:
91 filtered_date = self.days_ago(datetime.today(), number)
92
93 elif re.search(r'(\d+[mM]{1})', number_filter):
94 number = int(number_filter.lower().replace('m', ''))
95 if future:
96 filtered_date = self.months_future(datetime.today(), number)
97 else:
98 filtered_date = self.months_ago(datetime.today(), number)
99
100 elif re.search(r'(\d+[yY]{1})', number_filter):
101 number = int(number_filter.lower().replace('y', ''))
102 today = date.today()
103 if future:
104 year = today.year + number
105 else:
106 year = today.year - number
107 filtered_date = datetime(year, today.month, today.day)
108
109 return number, filtered_date
110
111 def validate(self, stamp_filter):
112 """
113 Validate a given filter. Filters can have the following notation:
114
115 - %Y-%m-%d: Times recorded at a given date
116
117 - %Y-%m-%d--%Y-%m-%d: Times recorded between two dates
118
119 - *%Y-%m-%d: Times recorded up to a given date
120
121 - %Y-%m-%d*: Times recorded from a given date
122
123 - %Y-%m-%d+sN[d|w|m|y]: Times recorded since the given date up to
124 N more days/weeks/months/years
125
126 - N...N[d|w|m|y]: Times recorded N...N days/weeks/months/years ago
127
128 Important: all date comparisons are made on datetime objects, using
129 00:00 as the time (first second of the given day). This means that
130 for range filters, the first day is included, but the second day is not
131 """
132 filter_from = None
133 filter_to = None
134
135 if stamp_filter is None:
136 return filter_from, filter_to
137
138 if '--' in stamp_filter:
139 filter_from, filter_to = stamp_filter.split('--')
140 filter_from = datetime.strptime(filter_from, self.date_format)
141 filter_to = datetime.strptime(filter_to, self.date_format)
142
143 elif stamp_filter.startswith('*'):
144 filter_to = datetime.strptime(stamp_filter, '*'+self.date_format)
145 filter_to = filter_to.replace(hour=0, minute=0, second=0)
146
147 elif stamp_filter.endswith('*'):
148 filter_from = datetime.strptime(stamp_filter, self.date_format+'*')
149 filter_from = filter_from.replace(hour=0, minute=0, second=0)
150
151 elif '+' in stamp_filter:
152 # "+" filtering works with a date following by "+", a number and
153 # a letter (d|w|m|y) which sets the number of days, months, years
154 # we would like to go into the future
155 filter_to, number = stamp_filter.split('+')
156 filter_to = datetime.strptime(filter_to, self.date_format)
157 number, filter_from = self.parse_number_filter(number)
158 filter_from = self.days_ago(filter_to, int(number))
159 else:
160 # Check if the user is asking for N days/weeks/months/years
161 number, filter_from = self.parse_number_filter(stamp_filter)
162 if number is None:
163 # no filtering found, maybe they are giving us a fixed date
164 try:
165 filter_from = datetime.strptime(stamp_filter,
166 self.date_format)
167 except:
168 # nothing to be used as a filter, go on, printing a warning
169 print('[warning] invalid date filter: ' + stamp_filter)
170 else:
171 filter_from = filter_from.replace(hour=0, minute=0,
172 second=0)
173 filter_to = filter_from + timedelta(days=1)
174
175 return filter_from, filter_to
Note: See TracBrowser for help on using the repository browser.