-
-
Notifications
You must be signed in to change notification settings - Fork 423
Expand file tree
/
Copy pathdate.py
More file actions
1230 lines (902 loc) · 31.3 KB
/
date.py
File metadata and controls
1230 lines (902 loc) · 31.3 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
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
# -*- coding: utf-8 -*-
from __future__ import division
import calendar
import math
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from .period import Period
from .formatting.difference_formatter import DifferenceFormatter
from .mixins.default import TranslatableMixin, FormattableMixing, TestableMixin
from .constants import (
DAYS_PER_WEEK, YEARS_PER_DECADE, YEARS_PER_CENTURY,
MONTHS_PER_YEAR,
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
)
from .exceptions import PendulumException
class Date(TranslatableMixin, FormattableMixing, TestableMixin, date):
# Names of days of the week
_days = {
SUNDAY: 'Sunday',
MONDAY: 'Monday',
TUESDAY: 'Tuesday',
WEDNESDAY: 'Wednesday',
THURSDAY: 'Thursday',
FRIDAY: 'Friday',
SATURDAY: 'Saturday'
}
# First day of week
_week_starts_at = MONDAY
# Last day of week
_week_ends_at = SUNDAY
# Weekend days
_weekend_days = [
SATURDAY,
SUNDAY
]
_MODIFIERS_VALID_UNITS = ['day', 'week', 'month', 'year', 'decade', 'century']
_diff_formatter = None
@classmethod
def instance(cls, dt):
"""
Return a new Date instance given a native date instance.
:param dt: The native date instance.
:type dt: date
:rtype: Date
"""
return cls(dt.year, dt.month, dt.day)
@classmethod
def create(cls, year=None, month=None, day=None):
"""
Create a new Date instance from a specific date.
If any of year, month or day are set to None their today() values will
be used.
:type year: int
:type month: int
:type day: int
:rtype: Date
"""
if any([year is None, month is None, day is None]):
now = date.today()
if year is None:
year = now.year
if month is None:
month = now.month
if day is None:
day = now.day
return cls(year, month, day)
@classmethod
def today(cls, tz=None):
"""
Create a Date instance for today.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Date
"""
if cls.has_test_now():
return cls.get_test_now()
return cls.create()
@classmethod
def yesterday(cls):
return cls.today().subtract(days=1)
@classmethod
def tomorrow(cls):
return cls.today().add(days=1)
### Getters/Setters
def year_(self, year):
return self._setter(year=year)
def month_(self, month):
return self._setter(month=month)
def day_(self, day):
return self._setter(day=day)
def _setter(self, **kwargs):
return self.replace(**kwargs)
@property
def day_of_week(self):
"""
Returns the day of the week (0-6).
:rtype: int
"""
return self.isoweekday() % 7
@property
def day_of_year(self):
"""
Returns the day of the year (1-366).
:rtype: int
"""
k = 1 if self.is_leap_year() else 2
return (
(275 * self.month) // 9
- k * ((self.month + 9) // 12)
+ self.day - 30
)
@property
def week_of_year(self):
return self.isocalendar()[1]
@property
def days_in_month(self):
return calendar.monthrange(self.year, self.month)[1]
@property
def week_of_month(self):
return int(math.ceil(self.day / DAYS_PER_WEEK))
@property
def age(self):
return self.diff().in_years()
@property
def quarter(self):
return int(math.ceil(self.month / 3))
### Special week days
@classmethod
def get_week_starts_at(cls):
"""
Get the first day of the week.
:rtype: int
"""
return cls._week_starts_at
@classmethod
def set_week_starts_at(cls, value):
"""
Set the first day of the week.
:type value: int
"""
if value not in cls._days:
raise ValueError('Invalid day of the week: {}'.format(value))
cls._week_starts_at = value
@classmethod
def get_week_ends_at(cls):
"""
Get the last day of the week.
:rtype: int
"""
return cls._week_ends_at
@classmethod
def set_week_ends_at(cls, value):
"""
Set the last day of the week.
:type value: int
"""
if value not in cls._days:
raise ValueError('Invalid day of the week: {}'.format(value))
cls._week_ends_at = value
@classmethod
def get_weekend_days(cls):
"""
Get weekend days.
:rtype: list
"""
return cls._weekend_days
@classmethod
def set_weekend_days(cls, values):
"""
Set weekend days.
:type value: list
"""
for value in values:
if value not in cls._days:
raise ValueError('Invalid day of the week: {}'
.format(value))
cls._weekend_days = values
# String Formatting
def to_date_string(self):
"""
Format the instance as date.
:rtype: str
"""
return self.format('%Y-%m-%d', formatter='classic')
def to_formatted_date_string(self):
"""
Format the instance as a readable date.
:rtype: str
"""
return self.format('%b %d, %Y', formatter='classic')
# COMPARISONS
def between(self, dt1, dt2, equal=True):
"""
Determines if the instance is between two others.
:type dt1: Date or date
:type dt2: Date or date
:param equal: Indicates if a > and < comparison shoud be used or <= and >=
:rtype: bool
"""
if dt1 > dt2:
dt1, dt2 = dt2, dt1
if equal:
return self >= dt1 and self <= dt2
return self > dt1 and self < dt2
def closest(self, dt1, dt2):
"""
Get the closest date from the instance.
:type dt1: Date or date
:type dt2: Date or date
:rtype: Date
"""
dt1 = self._get_date(dt1, True)
dt2 = self._get_date(dt2, True)
if self.diff(dt1).in_seconds() < self.diff(dt2).in_seconds():
return dt1
return dt2
def farthest(self, dt1, dt2):
"""
Get the farthest date from the instance.
:type dt1: Date or date
:type dt2: Date or date
:rtype: Date
"""
dt1 = self._get_date(dt1, True)
dt2 = self._get_date(dt2, True)
if self.diff(dt1).in_seconds() > self.diff(dt2).in_seconds():
return dt1
return dt2
def min_(self, dt=None):
"""
Get the minimum instance between a given instance (default utcnow)
and the current instance.
:type dt: Date or date
:rtype: Date
"""
if dt is None:
dt = Date.today()
if self < dt:
return self
return self._get_date(dt, True)
def minimum(self, dt=None):
"""
Get the minimum instance between a given instance (default now)
and the current instance.
:type dt: Date or date
:rtype: Date
"""
return self.min_(dt)
def max_(self, dt=None):
"""
Get the maximum instance between a given instance (default now)
and the current instance.
:type dt: Date or date
:rtype: Date
"""
if dt is None:
dt = Date.today()
if self > dt:
return self
return self._get_date(dt, True)
def maximum(self, dt=None):
"""
Get the maximum instance between a given instance (default utcnow)
and the current instance.
:type dt: Date or date
:rtype: Date
"""
return self.max_(dt)
def is_weekday(self):
"""
Determines if the instance is a weekday.
:rtype: bool
"""
return not self.is_weekend()
def is_weekend(self):
"""
Determines if the instance is a weekend day.
:rtype: bool
"""
return self.day_of_week in self._weekend_days
def is_yesterday(self):
"""
Determines if the instance is yesterday.
:rtype: bool
"""
return self == self.yesterday()
def is_today(self):
"""
Determines if the instance is today.
:rtype: bool
"""
return self == self.today()
def is_tomorrow(self):
"""
Determines if the instance is tomorrow.
:rtype: bool
"""
return self == self.tomorrow()
def is_future(self):
"""
Determines if the instance is in the future, ie. greater than now.
:rtype: bool
"""
return self > self.today()
def is_past(self):
"""
Determines if the instance is in the past, ie. less than now.
:rtype: bool
"""
return self < self.today()
def is_leap_year(self):
"""
Determines if the instance is a leap year.
:rtype: bool
"""
return calendar.isleap(self.year)
def is_long_year(self):
"""
Determines if the instance is a long year
See link `<https://en.wikipedia.org/wiki/ISO_8601#Week_dates>`_
:rtype: bool
"""
return Date(self.year, 12, 28).isocalendar()[1] == 53
def is_same_day(self, dt):
"""
Checks if the passed in date is the same day as the instance current day.
:type dt: Date or date
:rtype: bool
"""
return self == dt
def is_sunday(self):
"""
Checks if this day is a sunday.
:rtype: bool
"""
return self.day_of_week == SUNDAY
def is_monday(self):
"""
Checks if this day is a monday.
:rtype: bool
"""
return self.day_of_week == MONDAY
def is_tuesday(self):
"""
Checks if this day is a tuesday.
:rtype: bool
"""
return self.day_of_week == TUESDAY
def is_wednesday(self):
"""
Checks if this day is a wednesday.
:rtype: bool
"""
return self.day_of_week == WEDNESDAY
def is_thursday(self):
"""
Checks if this day is a thursday.
:rtype: bool
"""
return self.day_of_week == THURSDAY
def is_friday(self):
"""
Checks if this day is a friday.
:rtype: bool
"""
return self.day_of_week == FRIDAY
def is_saturday(self):
"""
Checks if this day is a saturday.
:rtype: bool
"""
return self.day_of_week == SATURDAY
def is_birthday(self, dt=None):
"""
Check if its the birthday. Compares the date/month values of the two dates.
:rtype: bool
"""
if dt is None:
dt = Date.today()
instance = self._get_date(dt, True)
return (self.month, self.day) == (instance.month, instance.day)
# ADDITIONS AND SUBSTRACTIONS
def add(self, years=0, months=0, weeks=0, days=0):
"""
Add duration to the instance.
:param years: The number of years
:type years: int
:param months: The number of months
:type months: int
:param weeks: The number of weeks
:type weeks: int
:param days: The number of days
:type days: int
:rtype: Date
"""
delta = relativedelta(
years=years,
months=months,
weeks=weeks,
days=days,
)
return self.instance(date(self.year, self.month, self.day) + delta)
def subtract(self, years=0, months=0, weeks=0, days=0):
"""
Remove duration from the instance.
:param years: The number of years
:type years: int
:param months: The number of months
:type months: int
:param weeks: The number of weeks
:type weeks: int
:param days: The number of days
:type days: int
:rtype: Date
"""
delta = relativedelta(
years=years,
months=months,
weeks=weeks,
days=days
)
return self.instance(date(self.year, self.month, self.day) - delta)
def add_timedelta(self, delta):
"""
Add timedelta duration to the instance.
:param delta: The timedelta instance
:type delta: datetime.timedelta
:rtype: Date
"""
return self.add(days=delta.days)
def subtract_timedelta(self, delta):
"""
Remove timedelta duration from the instance.
:param delta: The timedelta instance
:type delta: datetime.timedelta
:rtype: Date
"""
return self.subtract(days=delta.days)
def __add__(self, other):
if not isinstance(other, timedelta):
return NotImplemented
return self.add_timedelta(other)
def __sub__(self, other):
if isinstance(other, timedelta):
return self.subtract_timedelta(other)
try:
return self._get_date(other, True).diff(self, False)
except ValueError:
return NotImplemented
# DIFFERENCES
@property
def diff_formatter(self):
"""
Returns a DifferenceFormatter instance.
:rtype: DifferenceFormatter
"""
if not self.__class__._diff_formatter:
self.__class__._diff_formatter = DifferenceFormatter(self.__class__.translator())
return self.__class__._diff_formatter
def diff(self, dt=None, abs=True):
"""
Returns the difference between two Date objects as a Period.
:type dt: Date or None
:param abs: Whether to return an absolute interval or not
:type abs: bool
:rtype: Period
"""
if dt is None:
dt = self.today()
return Period(self, self._get_date(dt, True), absolute=abs)
def diff_for_humans(self, other=None, absolute=False, locale=None):
"""
Get the difference in a human readable format in the current locale.
When comparing a value in the past to default now:
1 day ago
5 months ago
When comparing a value in the future to default now:
1 day from now
5 months from now
When comparing a value in the past to another value:
1 day before
5 months before
When comparing a value in the future to another value:
1 day after
5 months after
:type other: Date
:param absolute: removes time difference modifiers ago, after, etc
:type absolute: bool
:param locale: The locale to use for localization
:type locale: str
:rtype: str
"""
return self.diff_formatter.diff_for_humans(self, other, absolute, locale)
# MODIFIERS
def start_of(self, unit):
"""
Returns a copy of the instance with the time reset
with the following rules:
* day: time to 00:00:00
* week: date to first day of the week and time to 00:00:00
* month: date to first day of the month and time to 00:00:00
* year: date to first day of the year and time to 00:00:00
* decade: date to first day of the decade and time to 00:00:00
* century: date to first day of century and time to 00:00:00
:param unit: The unit to reset to
:type unit: str
:rtype: Date
"""
if unit not in self._MODIFIERS_VALID_UNITS:
raise ValueError('Invalid unit "{}" for start_of()'.format(unit))
return getattr(self, '_start_of_{}'.format(unit))()
def end_of(self, unit):
"""
Returns a copy of the instance with the time reset
with the following rules:
* week: date to last day of the week
* month: date to last day of the month
* year: date to last day of the year
* decade: date to last day of the decade
* century: date to last day of century
:param unit: The unit to reset to
:type unit: str
:rtype: Date
"""
if unit not in self._MODIFIERS_VALID_UNITS:
raise ValueError('Invalid unit "%s" for end_of()' % unit)
return getattr(self, '_end_of_%s' % unit)()
def _start_of_day(self):
"""
Compatibility method.
:rtype: Date
"""
return self
def _end_of_day(self):
"""
Compatibility method
:rtype: Date
"""
return self
def _start_of_month(self):
"""
Reset the date to the first day of the month.
:rtype: Date
"""
return self.replace(self.year, self.month, 1)
def _end_of_month(self):
"""
Reset the date to the last day of the month.
:rtype: Date
"""
return self.replace(
self.year, self.month, self.days_in_month
)
def _start_of_year(self):
"""
Reset the date to the first day of the year.
:rtype: Date
"""
return self.replace(self.year, 1, 1)
def _end_of_year(self):
"""
Reset the date to the last day of the year.
:rtype: Date
"""
return self.replace(self.year, 12, 31)
def _start_of_decade(self):
"""
Reset the date to the first day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE
return self.replace(year, 1, 1)
def _end_of_decade(self):
"""
Reset the date to the last day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1
return self.replace(year, 12, 31)
def _start_of_century(self):
"""
Reset the date to the first day of the century.
:rtype: Date
"""
year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1
return self.replace(year, 1, 1)
def _end_of_century(self):
"""
Reset the date to the last day of the century.
:rtype: Date
"""
year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + YEARS_PER_CENTURY
return self.replace(year, 12, 31)
def _start_of_week(self):
"""
Reset the date to the first day of the week.
:rtype: Date
"""
dt = self
if self.day_of_week != self._week_starts_at:
dt = self.previous(self._week_starts_at)
return dt.start_of('day')
def _end_of_week(self):
"""
Reset the date to the last day of the week.
:rtype: Date
"""
dt = self
if self.day_of_week != self._week_ends_at:
dt = self.next(self._week_ends_at)
return dt.end_of('day')
def next(self, day_of_week=None):
"""
Modify to the next occurrence of a given day of the week.
If no day_of_week is provided, modify to the next occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:param day_of_week: The next day of week to reset to.
:type day_of_week: int or None
:rtype: Date
"""
if day_of_week is None:
day_of_week = self.day_of_week
if day_of_week < SUNDAY or day_of_week > SATURDAY:
raise ValueError('Invalid day of week')
dt = self.add(days=1)
while dt.day_of_week != day_of_week:
dt = dt.add(days=1)
return dt
def previous(self, day_of_week=None):
"""
Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:param day_of_week: The previous day of week to reset to.
:type day_of_week: int or None
:rtype: Date
"""
if day_of_week is None:
day_of_week = self.day_of_week
if day_of_week < SUNDAY or day_of_week > SATURDAY:
raise ValueError('Invalid day of week')
dt = self.subtract(days=1)
while dt.day_of_week != day_of_week:
dt = dt.subtract(days=1)
return dt
def first_of(self, unit, day_of_week=None):
"""
Returns an instance set to the first occurrence
of a given day of the week in the current unit.
If no day_of_week is provided, modify to the first day of the unit.
Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDAY.
Supported units are month, quarter and year.
:param unit: The unit to use
:type unit: str
:type day_of_week: int or None
:rtype: Date
"""
if unit not in ['month', 'quarter', 'year']:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
return getattr(self, '_first_of_{}'.format(unit))(day_of_week)
def last_of(self, unit, day_of_week=None):
"""
Returns an instance set to the last occurrence
of a given day of the week in the current unit.
If no day_of_week is provided, modify to the last day of the unit.
Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDAY.
Supported units are month, quarter and year.
:param unit: The unit to use
:type unit: str
:type day_of_week: int or None
:rtype: Date
"""
if unit not in ['month', 'quarter', 'year']:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
return getattr(self, '_last_of_{}'.format(unit))(day_of_week)
def nth_of(self, unit, nth, day_of_week):
"""
Returns a new instance set to the given occurrence
of a given day of the week in the current unit.
If the calculated occurrence is outside the scope of the current unit,
then raise an error. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
Supported units are month, quarter and year.
:param unit: The unit to use
:type unit: str
:type nth: int
:type day_of_week: int or None
:rtype: Date
"""
if unit not in ['month', 'quarter', 'year']:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
dt = getattr(self, '_nth_of_{}'.format(unit))(nth, day_of_week)
if dt is False:
raise PendulumException('Unable to find occurence {} of {} in {}'.format(
nth, self._days[day_of_week], unit))
return dt
def _first_of_month(self, day_of_week):
"""
Modify to the first occurrence of a given day of the week
in the current month. If no day_of_week is provided,
modify to the first day of the month. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:type day_of_week: int
:rtype: Date
"""
dt = self
if day_of_week is None:
return dt.day_(1)
month = calendar.monthcalendar(dt.year, dt.month)
calendar_day = (day_of_week - 1) % 7
if month[0][calendar_day] > 0:
day_of_month = month[0][calendar_day]
else:
day_of_month = month[1][calendar_day]
return dt.day_(day_of_month)
def _last_of_month(self, day_of_week=None):
"""
Modify to the last occurrence of a given day of the week
in the current month. If no day_of_week is provided,
modify to the last day of the month. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:type day_of_week: int or None
:rtype: Date
"""
dt = self
if day_of_week is None:
return dt.day_(self.days_in_month)
month = calendar.monthcalendar(dt.year, dt.month)
calendar_day = (day_of_week - 1) % 7