Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / dateparse / dateparse_utils.py
index d0d1eca8e4c564d2fec240b95576e8eac4d80596..2e6eabde5ee155f1ca81e4c1f0c3f542f96dfb96 100755 (executable)
@@ -3,6 +3,8 @@
 # pylint: disable=W0201
 # pylint: disable=R0904
 
+# © Copyright 2021-2022, Scott Gasch
+
 """Parse dates in a variety of formats."""
 
 import datetime
@@ -346,7 +348,7 @@ class DateParser(dateparse_utilsListener):
                 return 5
 
     def _parse_normal_date(self) -> datetime.date:
-        if 'dow' in self.context:
+        if 'dow' in self.context and 'month' not in self.context:
             d = self.today
             while d.weekday() != self.context['dow']:
                 d += datetime.timedelta(days=1)
@@ -670,10 +672,10 @@ class DateParser(dateparse_utilsListener):
             del self.context['dow']
             self.context['delta_unit'] = dow
 
-            # For the nth Fooday in Month, start at the 1st of the
-            # month and count ahead N Foodays.  For the last Fooday in
-            # Month, start at the last of the month and count back one
-            # Fooday.
+            # For the nth Fooday in Month, start at the last day of
+            # the previous month count ahead N Foodays.  For the last
+            # Fooday in Month, start at the last of the month and
+            # count back one Fooday.
             if n == -1:
                 month += 1
                 if month == 13:
@@ -682,17 +684,16 @@ class DateParser(dateparse_utilsListener):
                 tmp_date = datetime.date(year=year, month=month, day=1)
                 tmp_date = tmp_date - datetime.timedelta(days=1)
 
-                self.context['year'] = tmp_date.year
-                self.context['month'] = tmp_date.month
-                self.context['day'] = tmp_date.day
-
                 # The delta adjustment code can handle the case where
                 # the last day of the month is the day we're looking
                 # for already.
             else:
-                self.context['year'] = year
-                self.context['month'] = month
-                self.context['day'] = 1
+                tmp_date = datetime.date(year=year, month=month, day=1)
+                tmp_date = tmp_date - datetime.timedelta(days=1)
+
+            self.context['year'] = tmp_date.year
+            self.context['month'] = tmp_date.month
+            self.context['day'] = tmp_date.day
             self.main_type = DateParser.PARSE_TYPE_BASE_AND_OFFSET_EXPR
         except Exception as e:
             raise ParseException(f'Invalid nthWeekday expression: {ctx.getText()}') from e