/
calendar.py
1818 lines (1527 loc) · 53.6 KB
/
calendar.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sortedcontainers
import collections
import collections.abc
import datetime
import numbers
import dateutil.rrule
import warnings
import doubledate.utils as utils
import doubledate.constants as constants
class BD:
"""
Business day.
Parameters
----------
index : int
day of the frequency
frequency : str
one of 'D','W','M','Q','H' or 'Y'
base : 0 (default), 1
whether to consider the index 1-based or 0-based
"""
def __init__(self, index: int, frequency: str = "M", *, base: int = 0):
if not isinstance(index, numbers.Integral):
raise TypeError(
f"Expected index to be an integer, received {type(index).__name__}"
)
self.index = index
if frequency not in ["D", "W", "M", "Q", "H", "Y"]:
raise ValueError(
f"Expected frequency to be one of 'D','W','M','Q','H' or 'Y', received '{frequency}'"
)
self.frequency = frequency
if base not in (0, 1):
raise ValueError(f"Expected base to be one of 0 or 1, received {base}")
self.base = base
def resolve(self, calendar, onerror: str = "skip"):
"""
Returns a new Calendar containing only the n'th business day each frequency.
Allowed values for the onerror parameter:
- 'skip' to skip periods where the n'th business day is not defined
- 'first' to fallback to the first date in the period when the n'th
business day is not defined
- 'last' to fallback to the last date in the period when the n'th
business day is not defined
- 'raise' to raise an error if the n'th business day is not defined
Parameters
----------
calendar : Calendar
the calendar from which to compute the n'th business day
onerror : str
handling policy for periods the n'th business day is not defined
Returns
-------
Calendar
Calendar containing the n'th business day each frequency
"""
if self.frequency == "D":
return calendar
dates = []
for subcal in calendar.resample(self.frequency):
try:
dates.append(subcal[self.index - self.base])
except Exception as e:
if onerror == constants.RAISE:
raise e
elif onerror == "drop" or onerror == "skip":
pass
elif onerror == "last":
dates.append(subcal[-1])
elif onerror == "first":
dates.append(subcal[0])
elif callable(onerror):
dates.append(onerror(subcal))
else:
raise ValueError(
f"expected onerror to be one of 'raise', 'skip', 'last', 'first' or a callable, received {onerror}"
)
return Calendar(dates)
class Calendar:
"""
Immutable, sorted set of dates.
Parameters
----------
dates : iterable
list of datetime objects
Example
-------
.. code-block::
>>> import datetime
>>> import doubledate as dtwo
>>> holidays = [
... datetime.date(2022, 1, 17),
... datetime.date(2022, 5, 30),
... datetime.date(2022, 6, 4),
... datetime.date(2022, 9, 5),
... datetime.date(2022, 11, 11),
... datetime.date(2022, 12, 24),
... datetime.date(2022, 12, 26)
... ]
>>> dtwo.Calendar(holidays)
<doubledate.Calendar at 0x7fd0fa4cfa60>
Raises
------
TypeError
if dates is not an iterable of datetime objects
"""
def __init__(self, dates):
if not all([isinstance(item, datetime.date) for item in dates]):
raise TypeError("Calendar expected an iterable of date objects")
self.__dates__ = sortedcontainers.SortedSet([date for date in dates])
self.__datemaps__ = {}
def __hash__(self):
"""
Returns the hash of the Calendar.
"""
return hash((date for date in self))
@classmethod
def create(
cls, freq="D", *, starting=None, ending=None, rrule=None, dtype=None, **kwargs
):
"""
Create a new calendar, wrapping :code:`dateutil.rrule`
Parameters
----------
freq : str, int
The calendar frequency; one of:
- :Code:`Y` for yearly
- :Code:`M` for monthly
- :Code:`W` for weekly (or any dayised variant, e.g. :code:`W-MON`)
- :Code:`D` for daily
- :Code:`B` for daily except for Saturday and Sunday
- :Code:`H` for hourly
- :Code:`MIN` for minutely
- :Code:`S` for secondly
or any :code:`dateutil.rrule` constant (e.g. :code:`dateutil.rrule.MONTHLY`)
starting : datetime
The starting date in the calendar.
Alias for :code:`dstart` in :code:`dateutil.rrule.rrule`.
ending : datetime
The last date in the calendar.
Alias for :code:`until` in :code:`dateutil.rrule.rrule`.
rrule : str, dateutil.rrule.rrule
A recurrence rule.
If given a :code:`str`, this will be evaluated as a
:code:`dateutil.rrule.rrulestr` with the :code:`dstart`
dtype : None, type
The datetime type (e.g. :code:`pd.Timestamp`).
If None is provided, defaults to :code:`datetime.datetime`, which
is the default of the :dateutil.rrule` library.
**kwargs : dict
additional arguments to pass to :code:`dateutil.rrule.rrule`
Examples
--------
::
>>> import doubledate as dtwo
# every day in 2023
>>> dtwo.Calendar.create(
... "D",
... starting=dtwo.date(2023, 1, 1),
... until=dtwo.date(2023, 12, 31)
... )
<doubledate.calendar.Calendar at 0x17045b0f430>
# the first day each month in 2018-2023
>>> dtwo.Calendar.create(
... "M",
... starting=dtwo.date(2018, 1, 1),
... until=dtwo.date(2023, 12, 31)
... )
<doubledate.calendar.Calendar at 0x17045b0f430>
# the first Monday each month in 2018-2023
>>> dtwo.Calendar.create(
... "M",
... starting=dtwo.date(2018, 1, 1),
... until=dtwo.date(2023, 12, 31),
... byweekday=dtwo.MO
... )
<doubledate.calendar.Calendar at 0x17045b0f430>
"""
if rrule is not None:
if isinstance(rrule, str):
rrule = dateutil.rrule.rrulestr(rrule, dtstart=starting)
return cls([d if dtype is None else dtype(d) for d in rrule])
frequencies = {
"Y": dateutil.rrule.YEARLY,
"M": dateutil.rrule.MONTHLY,
"W": dateutil.rrule.WEEKLY,
"D": dateutil.rrule.DAILY,
"H": dateutil.rrule.HOURLY,
"MIN": dateutil.rrule.MINUTELY,
"S": dateutil.rrule.SECONDLY,
}
weekdays = {
"MON": dateutil.rrule.MO,
"MO": dateutil.rrule.MO,
0: dateutil.rrule.MO,
"TUE": dateutil.rrule.TU,
"TU": dateutil.rrule.TU,
1: dateutil.rrule.TU,
"WED": dateutil.rrule.WE,
"WE": dateutil.rrule.WE,
2: dateutil.rrule.WE,
"THU": dateutil.rrule.TH,
"TH": dateutil.rrule.TH,
3: dateutil.rrule.TH,
"FRI": dateutil.rrule.FR,
"FR": dateutil.rrule.FR,
4: dateutil.rrule.FR,
"SAT": dateutil.rrule.SA,
"SA": dateutil.rrule.SA,
5: dateutil.rrule.SA,
"SUN": dateutil.rrule.SU,
"SU": dateutil.rrule.SU,
6: dateutil.rrule.SU,
}
if freq == "B":
freq, kwargs["byweekday"] = "D", dateutil.rrule.weekdays[:-2]
if freq in ["W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN"]:
freq, kwargs["byweekday"] = "D", freq[-3:]
if "byweekday" in kwargs:
kwargs["byweekday"] = [weekdays.get(d, d) for d in kwargs["byweekday"]]
return cls.create(
rrule=dateutil.rrule.rrule(
frequencies.get(freq, freq),
**{"dtstart": starting, "until": ending, **kwargs},
)
)
@classmethod
def generate(cls, starting: datetime.date, ending: datetime.date):
"""
Creates a new calendar with all the calendar days between the starting and
ending dates, with both bounds included.
Parameters
----------
starting : datetime.date
the starting date
ending : datetime.date
the ending date
Returns
-------
Calendar
the calendar
Example
-------
.. code-block::
>>> import datetime
>>> import doubledate as dtwo
>>> calendar = dtwo.Calendar.generate(
... starting=datetime.date(2021,1,1),
... ending=datetime.date(2021,12,31)
... )
>>> len(calendar)
365
>>> calendar[0]
datetime.date(2021,1,1)
>>> calendar[-1]
datetime.date(2021,12,31)
"""
warnings.warn(
"Calendar.generate is marked for deprecation and may be removed in future versions. Use Calendar.create instead",
DeprecationWarning,
)
if not all(isinstance(d, datetime.date) for d in (starting, ending)):
raise TypeError("Expected starting and ending dates to be datetime objects")
return cls(
[
starting + datetime.timedelta(days=i)
for i in range((ending - starting).days + 1)
]
)
@property
def last(self) -> datetime.date:
"""
Returns the last date in the calendar.
Returns
-------
datetime.date
The last date in the calendar
Raises
------
KeyError
if the calendar is empty
See also
--------
Calendar.first
Returns the first date in the calendar
Calendar.end
Alias
"""
return self[-1]
@property
def end(self) -> datetime.date:
"""
Returns the last date in the calendar.
Returns
-------
datetime.date
The last date in the calendar
Raises
------
KeyError
if the calendar is empty
See also
--------
Calendar.start
Returns the first date in the calendar
Calendar.last
Alias
"""
return self.last
@property
def first(self) -> datetime.date:
"""
Returns the first date in the calendar.
Returns
-------
datetime.date
The first date in the calendar
Raises
------
KeyError
if the calendar is empty
See also
--------
Calendar.start
alias
Calendar.last
Returns the last date in the calendar
"""
return self[0]
@property
def start(self) -> datetime.date:
"""
Returns the first date in the calendar.
Returns
-------
datetime.date
The first date in the calendar
Raises
------
KeyError
if the calendar is empty
See also
--------
Calendar.first
alias
Calendar.end
Returns the last date in the calendar
"""
return self.first
@property
def dates(self) -> list:
"""
Returns the dates as a list.
Returns
-------
list
List of dates
"""
return list(self.__dates__)
def __len__(self) -> int:
"""
Returns the length of the calendar.
Returns
-------
int
Number of days in teh calendar
"""
return len(self.__dates__)
def __contains__(self, date) -> bool:
"""
Returns True if the date is in the calendar.
Returns
-------
bool
True if date is in the calendar
"""
return date in self.__dates__
def index(self, date) -> int:
"""
Returns the index (0-based position) of the date.
Parameters
----------
date : datetime
the date whose index is searched
Raises
------
ValueError
If date is not in calendar
Returns
-------
int
Position (0-based) of the date
"""
if isinstance(date, collections.abc.Iterable):
return [self.index(d) for d in date]
return self.__dates__.index(date)
def __iter__(self):
"""
Returns the iterator of the dates.
"""
return iter(self.__dates__)
def __getitem__(self, value):
"""
Retrieves a date by index or slices a calendar.
If `value` is a slice, the start and stop values can be
either integers or datetime.date objects.
Returns
-------
datetime.date
if passed an index
Calendar
if passed a slice
Raises
------
TypeError
if value is neither an integer nor a slice
KeyError
if the index is out of range
"""
if isinstance(value, slice):
if isinstance(value.start, datetime.date):
value = slice(self.__dates__.bisect_left(value.start), value.stop)
if isinstance(value.stop, datetime.date):
value = slice(value.start, self.__dates__.bisect_right(value.stop))
return Calendar(self.__dates__.__getitem__(value))
return self.__dates__.__getitem__(value)
def __add__(self, other):
"""
Alias for union.
Parameter
---------
other : iterable
An iterable of datetime.date objects
Returns
-------
Calendar
"""
if isinstance(other, datetime.date):
return self.union([other])
return self.union(other)
def __eq__(self, other):
"""
Returns True if all dates are in other, and all dates of other are in self.
Parameters
----------
other : iterable
the compared calendar
Returns
-------
Calendar
"""
try:
for date in self:
if date not in other:
return False
for date in other:
if date not in self:
return False
return True
except Exception:
return False
def union(self, *others):
"""
Combines two calendars by combining dates in self and other.
Parameters
----------
others : iterables
Returns
-------
Calendar
The union of self with others
"""
return Calendar(self.__dates__.union(*others))
def difference(self, *others):
"""
Returns a calendar containing dates in self and not in others.
Parameters
----------
others : iterables
Iterables of datetime.date objects
Returns
-------
Calendar
The difference of this calendar with others
"""
return Calendar(self.__dates__.difference(*others))
def intersection(self, *others):
"""
Returns a calendar containing dates from self which are also in all the others.
Parameters
----------
others : iterables
Iterables of datetime.date objects
Returns
-------
Calendar
"""
return Calendar(self.__dates__.intersection(*others))
def join(self, other, *, on=None) -> "Calendar":
"""
Returns a new :code:`Calendar` containing dates in *self* (to and including the
given :code:`on` date) and dates in other (from and including the :code:`on`
date).
If :code:`on` is not provided, defaults to the last date
in *self*.
Parameters
----------
other : iterable
Other calendar
on : datetime.date
date from which to join the two calendars together
Returns
-------
Calendar
Examples
-------
::
>>> import doubledate as dtwo
>>> this = dtwo.Calendar(
... [
... dtwo.date(2023,1,1),
... dtwo.date(2023,2,1),
... dtwo.date(2023,3,1),
... ]
... )
>>> that = dtwo.Calendar(
... [
... dtwo.date(2023,1,15),
... dtwo.date(2023,2,15),
... dtwo.date(2023,3,15),
... ]
... )
>>> this.join(that)
<doubledate.calendar.Calendar at 0x17045b0e830>
>>> this.join(that).dates
[datetime.date(2023, 1, 1), datetime.date(2023, 2, 1),
datetime.date(2023, 3, 1), datetime.date(2023, 3, 15)]
>>> this.join(that, on=dtwo.date(2023,2,15)).dates
[datetime.date(2023, 1, 1), datetime.date(2023, 2, 1),
datetime.date(2023, 2, 15), datetime.date(2023, 3, 15)]
"""
if on is None:
return self.union(Calendar(other)[self.end :])
return self[:on].union(Calendar(other)[on:])
def filter(
self,
func=None,
*,
year: int = None,
semester: int = None,
quarter: int = None,
month: int = None,
week: int = None,
weekday: str = None,
):
"""
Filters and returns a new calendar from this calendar based on a criteria.
Allowed criteria are:
- either a filtering function (lambda)
- one or several filtering frequencies as named arguments
Parameters
----------
func : function, optional
a filtering function (receives each date as argument)
year : int, optional
pass a value to filter dates of the given year only
semester : int, optional (1 or 2)
pass a value to filter dates of the given semester only
quarter : int, optional (1, 2, 3, or 4)
pass a value to filter dates of the given quarter only
month : int, optional (1 through 12)
pass a value to filter dates of the given month only
week : int, optional (1 through 53)
pass a value to filter dates of the given week number only
weekday : int, optional (0 through 6)
pass a value to filter dates of the given weekday only
Monday = 0, Tuesday = 1... Sunday = 6
Returns
-------
Calendar
Example
-------
Filter dates from 3Q 2020
>>> calendar = Calendar(dates) #assume dates is a list of dates
>>> calendar.filter(year=2020, quarter=3)
Filter Mondays
>>> calendar = Calendar(dates)
>>> calendar.filter(lambda date: date.weekday() == 0)
"""
if func is not None:
if not callable(func):
raise ValueError(
"Filter accepts either a function, one or several named arguments"
)
return Calendar([date for date in self if func(date)])
if all(
[arg is None for arg in [year, semester, quarter, month, week, weekday]]
):
raise ValueError(
"You need to provide one of year, semester, quarter, month, week, weekday"
)
dates = list(self.__dates__)
if year is not None:
dates = list(filter(lambda date: date.year == year, dates))
if semester is not None:
dates = list(filter(lambda date: utils.semester(date) == semester, dates))
if quarter is not None:
dates = list(filter(lambda date: utils.quarter(date) == quarter, dates))
if month is not None:
dates = list(filter(lambda date: date.month == month, dates))
if week is not None:
dates = list(filter(lambda date: date.isocalendar()[1] == week, dates))
if weekday is not None:
dates = list(filter(lambda date: date.weekday() == weekday, dates))
return Calendar(dates)
def weekdays(self):
"""
Filters out all the weekends (Saturdays and Sundays)
Returns
-------
Calendar
Calendar excluding any week-ends (Sat and Sun)
See also
--------
Calendar.weekends
Filter out all the weekdays
Calendar.filter
Filter out days based on a callback
"""
return self.filter(lambda date: date.weekday() not in [5, 6])
def weekends(self):
"""
Filters out all the weekdays (Mon, ..., Fri)
Returns
-------
Calendar
Calendar excluding any weekdays (Mon, ..., Fri)
See also
--------
Calendar.weekdays
Filter out all the weekends
Calendar.filter
Filter out days based on a callback
"""
return self.filter(lambda date: date.weekday() in [5, 6])
def inverse(self, starting: datetime.date = None, ending: datetime.date = None):
"""
Returns a calendar with all dates between :code:`starting` and :code:`ending`,
excluding any days in this calendar.
Parameters
----------
starting : datetime.date
the starting date of the new calendar (defaults to :code:`calendar[0]`)
ending : datetime.date
the ending date of the new calendar (defaults to :code:`calendar[-1]`)
Returns
-------
Calendar
Inverse of this calendar
Example
-------
Compute the open weekdays in 2022 from a list of holidays
>>> import datetime
>>> holidays = [
... datetime.date(2022, 1, 17),
... datetime.date(2022, 5, 30),
... datetime.date(2022, 6, 4),
... datetime.date(2022, 9, 5),
... datetime.date(2022, 11, 11),
... datetime.date(2022, 12, 24),
... datetime.date(2022, 12, 26)
... ]
>>> calendar = dtwo.Calendar(holidays).inverse(
... datetime.date(2022,1,1), datetime.date(2022, 12, 31)
... ).weekdays()
"""
if starting is None:
starting = self[0]
if ending is None:
ending = self[-1]
dates = []
for i in range((ending - starting).days + 1):
if starting + datetime.timedelta(i) not in self:
dates.append(starting + datetime.timedelta(i))
return Calendar(dates)
def dayof(self, frequency: str, *, base: int = 1):
"""
Returns a :code:`datemap` mapping dates to their index in the given frequency.
The frequency can be one of:
- :code:`W` for day of week (assumes week starts on Monday)
- :code:`W-MON` for day of week (assumes week starts on Monday)
- :code:`W-TUE` for day of week (assumes week starts on Tuesday)
- :code:`W-WED` for day of week (assumes week starts on Wednesday)
- :code:`W-THU` for day of week (assumes week starts on Thursay)
- :code:`W-FRI` for day of week (assumes week starts on Friday)
- :code:`W-SAT` for day of week (assumes week starts on Saturday)
- :code:`W-SUN` for day of week (assumes week starts on Sunday)
- :code:`M` for day of month
- :code:`Q` for day of quarter
- :code:`T` for day of trimester
- :code:`H` for day of semester (half year)
- :code:`Y` for day of year
Parameters
----------
frequency : str
the frequency
base : int
the index of the first day each frequency
Returns
-------
datemap
The datemap
Note
----
The default base is 1
Note
----
As the Calendar is immutable, the `datemap`
is cached for efficiency. Repeatedly calling :code:`calendar.dayof("M")`
should be of complexity 1 after the first call.
Example
-------
>>> calendar = Calendar(dates)
>>> calendar.dayof("M")[datetime.date(2021,1,3)]
1
"""
if ("dayof", frequency, base) not in self.__datemaps__:
self.__datemaps__[("dayof", frequency, base)] = utils.dayof(
frequency, calendar=self, base=base
)
return self.__datemaps__[("dayof", frequency, base)]
def daysfrom(self, frequency: str):
"""
Returns a :code:`datemap` mapping dates to the number of dates since the start
of the given frequency.
Parameters
----------
frequency : str,
the frequency at which to reset the counter
base : int
the index of the first day each frequency
Returns
-------
datemap
"""
if ("daysfrom", frequency) not in self.__datemaps__:
self.__datemaps__[("daysfrom", frequency)] = utils.daysfrom(
frequency, calendar=self
)
return self.__datemaps__[("daysfrom", frequency)]
def daysto(self, frequency: str):
"""
Returns a :code:`datemap` mapping dates to the number of dates to the end of the
given frequency.
Returns
-------
datemap
"""
if ("daysto", frequency) not in self.__datemaps__:
self.__datemaps__[("daysto", frequency)] = utils.daysto(
frequency, calendar=self
)
return self.__datemaps__[("daysto", frequency)]
def daysbetween(
self, this: datetime.date, that: datetime.date, bounds: str = "left"
) -> int:
"""
Returns the number of open days between two dates.
Parameters
----------
this : datetime.date
the left-bound of the calendar
that : datetime.date
the right-bound of the calenar
bounds : str, optional
whether to include this or that in the count
one of 'both', 'left' (default) or 'right' or None
Returns
--------
int
The number of dates between this and that
"""
if bounds == "both":
return len(
self.filter(lambda date: min(this, that) <= date <= max(this, that))
)
if bounds == "left":
return len(
self.filter(lambda date: min(this, that) <= date < max(this, that))
)
if bounds == "right":
return len(
self.filter(lambda date: min(this, that) < date <= max(this, that))
)
if bounds is None:
return len(
self.filter(lambda date: min(this, that) < date < max(this, that))
)
raise ValueError(
f"bounds should be one of 'both', 'left' or 'right', {bounds} given"
)
def offset(self, date: datetime.date, days: int) -> datetime.date:
"""
Returns the date in the calendar offset by n days.
Parameters
----------
date : datetime.date
the reference date
days : int
the offset
Returns
-------
offsetted : datetime.date
the date in the calendar days-away from the given date
"""
if isinstance(date, collections.abc.Iterable):
return [self.offset(date=d, days=days) for d in date]
if not date in self:
raise ValueError(f"{date} is not in the calendar")
if self.index(date) + days < 0:
raise IndexError(f"Out of bounds")
if self.index(date) + days >= len(self):
raise IndexError(f"Out of bounds")
return self[self.index(date) + days]
def groupby(self, grouper):
"""
Group dates by the grouper parameter.
Allowed values for the grouper:
- callable - the callable will receive the date and must return a hashable value
- frequency criterion - a string representing a frequency
Frequency criteria include:
- :code:`W`: group by week number each year (same as :code:`W-SUN`)
- :code:`W-MON`: to :code:`W-SUN` group week ending on a particular weekday
- :code:`M`: group by month each year
- :code:`Q`: group by quarter each year
- :code:`H`: group by semester each year
- :code:`Y`: group by year each year
Parameters
----------
grouper : str, callable
the criterion to group dates by
Returns
-------
:class:`doubledate.calendar.Collection`