-
-
Notifications
You must be signed in to change notification settings - Fork 423
Expand file tree
/
Copy pathpendulum.py
More file actions
2004 lines (1506 loc) · 54.8 KB
/
pendulum.py
File metadata and controls
2004 lines (1506 loc) · 54.8 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 datetime
import warnings
import pendulum
from .date import Date
from .time import Time
from .period import Period
from .exceptions import PendulumException
from .tz import Timezone, UTC, FixedTimezone, local_timezone
from .tz.timezone_info import TimezoneInfo
from .parsing import parse
from .helpers import add_duration
from .formatting import FORMATTERS
from .constants import (
YEARS_PER_CENTURY, YEARS_PER_DECADE,
MONTHS_PER_YEAR,
MINUTES_PER_HOUR, SECONDS_PER_MINUTE,
SECONDS_PER_DAY,
SUNDAY, SATURDAY
)
class Pendulum(Date, datetime.datetime):
# Formats
ATOM = '%Y-%m-%dT%H:%M:%S%_z'
COOKIE = '%A, %d-%b-%Y %H:%M:%S %Z'
ISO8601 = '%Y-%m-%dT%H:%M:%S%_z'
ISO8601_EXTENDED = '%Y-%m-%dT%H:%M:%S.%f%_z'
RFC822 = '%a, %d %b %y %H:%M:%S %z'
RFC850 = '%A, %d-%b-%y %H:%M:%S %Z'
RFC1036 = '%a, %d %b %y %H:%M:%S %z'
RFC1123 = '%a, %d %b %Y %H:%M:%S %z'
RFC2822 = '%a, %d %b %Y %H:%M:%S %z'
RFC3339 = '%Y-%m-%dT%H:%M:%S%_z'
RFC3339_EXTENDED = '%Y-%m-%dT%H:%M:%S.%f%_z'
RSS = '%a, %d %b %Y %H:%M:%S %z'
W3C = '%Y-%m-%dT%H:%M:%S%_z'
_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=UTC)
_TRANSITION_RULE = Timezone.POST_TRANSITION
_MODIFIERS_VALID_UNITS = [
'second', 'minute', 'hour',
'day', 'week', 'month', 'year',
'decade', 'century'
]
@classmethod
def _safe_create_datetime_zone(cls, obj):
"""
Creates a timezone from a string, Timezone, TimezoneInfo or integer offset.
:param obj: str or Timezone or TimezoneInfo or int or None
:rtype: Timezone
"""
if isinstance(obj, TimezoneInfo):
return obj.tz
if obj is None or obj == 'local':
return cls._local_timezone()
if isinstance(obj, (int, float)):
timezone_offset = obj * 60 * 60
return FixedTimezone.load(timezone_offset)
elif isinstance(obj, datetime.tzinfo) and not isinstance(obj, Timezone):
# pytz
if hasattr(obj, 'localize'):
return cls._timezone(obj.zone)
return FixedTimezone.load(obj.utcoffset(None).total_seconds())
return cls._timezone(obj)
@classmethod
def _local_timezone(cls):
"""
Returns the local timezone using tzlocal.get_localzone
or the TZ environment variable.
:rtype: Timezone
"""
return local_timezone()
@classmethod
def _timezone(cls, zone):
"""
Returns a timezone given its name.
:param zone: The name of the timezone.
:type zone: str
:rtype: Timezone
"""
if isinstance(zone, Timezone):
return zone
return Timezone.load(zone)
def __new__(cls, year, month, day,
hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, fold=None):
"""
Constructor.
This will just create a dummy datetime. The heavy lifting will be done
in __init__().
:type year: int or str
"""
obj = super(Pendulum, cls).__new__(cls, year, month, day, hour, minute, second, microsecond, None)
return obj
def __init__(self, year, month, day,
hour=0, minute=0, second=0, microsecond=0,
tzinfo=UTC, fold=None):
# If a TimezoneInfo is passed we do not convert
if isinstance(tzinfo, TimezoneInfo):
self._tz = tzinfo.tz
self._year = year
self._month = month
self._day = day
self._hour = hour
self._minute = minute
self._second = second
self._microsecond = microsecond
self._tzinfo = tzinfo
if fold is None:
# Converting rule to fold value
if self._TRANSITION_RULE == Timezone.POST_TRANSITION:
fold = 1
else:
fold = 0
self._fold = fold
dt = datetime.datetime(
year, month, day,
hour, minute, second, microsecond,
tzinfo
)
else:
self._tz = self._safe_create_datetime_zone(tzinfo)
# Support for explicit fold attribute
if fold is None:
transition_rule = self._TRANSITION_RULE
# Converting rule to fold value
if self._TRANSITION_RULE == Timezone.POST_TRANSITION:
fold = 1
else:
fold = 0
elif fold == 1:
transition_rule = Timezone.POST_TRANSITION
else:
transition_rule = Timezone.PRE_TRANSITION
dt = self._tz.convert(datetime.datetime(
year, month, day,
hour, minute, second, microsecond
), dst_rule=transition_rule)
self._year = dt.year
self._month = dt.month
self._day = dt.day
self._hour = dt.hour
self._minute = dt.minute
self._second = dt.second
self._microsecond = dt.microsecond
self._tzinfo = dt.tzinfo
self._fold = fold
self._timestamp = None
self._int_timestamp = None
self._datetime = dt
@classmethod
def instance(cls, dt, tz=UTC):
"""
Create a Pendulum instance from a datetime one.
:param dt: A datetime instance
:type dt: datetime.datetime
:param tz: The timezone
:type tz: Timezone or TimeZoneInfo or str or None
:rtype: Pendulum
"""
tz = dt.tzinfo or tz
# Checking for pytz/tzinfo
if isinstance(tz, datetime.tzinfo) and not isinstance(tz, (Timezone, TimezoneInfo)):
# pytz
if hasattr(tz, 'localize'):
tz = tz.zone
else:
# We have no sure way to figure out
# the timezone name, we fallback
# on a fixed offset
tz = dt.utcoffset().total_seconds() / 3600
return cls(
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.microsecond,
tzinfo=tz
)
@classmethod
def parse(cls, time=None, tz=UTC, **options):
"""
Create a Pendulum instance from a string.
:param time: The time string
:type time: str
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
if time is None:
return cls.now(tz)
if time == 'now':
return cls.now(None)
parsed = parse(time, **options)
if parsed['offset'] is None:
tz = tz
else:
tz = parsed['offset'] / 3600
return cls(
parsed['year'], parsed['month'], parsed['day'],
parsed['hour'], parsed['minute'], parsed['second'],
parsed['subsecond'],
tzinfo=tz
)
@classmethod
def now(cls, tz=None):
"""
Get a Pendulum instance for the current date and time.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or int or None
:rtype: Pendulum
"""
# If the class has a test now set and we are trying to create a now()
# instance then override as required
if cls.has_test_now():
test_instance = cls.get_test_now()
if tz is not None and tz != test_instance.timezone:
test_instance = test_instance.in_timezone(tz)
return test_instance
if tz is None or tz == 'local':
dt = datetime.datetime.now()
elif tz is UTC or tz == 'UTC':
dt = datetime.datetime.utcnow().replace(tzinfo=UTC)
else:
dt = datetime.datetime.utcnow().replace(tzinfo=UTC)
tz = cls._safe_create_datetime_zone(tz)
dt = tz.convert(dt)
return cls.instance(dt, tz)
@classmethod
def utcnow(cls):
"""
Get a Pendulum instance for the current date and time in UTC.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
return cls.now(UTC)
@classmethod
def today(cls, tz=None):
"""
Create a Pendulum instance for today.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
return cls.now(tz).start_of('day')
@classmethod
def tomorrow(cls, tz=None):
"""
Create a Pendulum instance for tomorrow.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
return cls.today(tz).add(days=1)
@classmethod
def yesterday(cls, tz=None):
"""
Create a Pendulum instance for yesterday.
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
return cls.today(tz).subtract(days=1)
@classmethod
def create(cls, year=None, month=None, day=None,
hour=0, minute=0, second=0, microsecond=0,
tz=UTC):
"""
Create a new Pendulum instance from a specific date and time.
If any of year, month or day are set to None their now() values will
be used.
:type year: int
:type month: int
:type day: int
:type hour: int
:type minute: int
:type second: int
:type microsecond: int
:type tz: tzinfo or str or int or None
:rtype: Pendulum
"""
tz = cls._safe_create_datetime_zone(tz)
if any([year is None, month is None, day is None]):
if cls.has_test_now():
now = cls.get_test_now().in_tz(tz)
else:
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
now = tz.convert(now)
if year is None:
year = now.year
if month is None:
month = now.month
if day is None:
day = now.day
dt = datetime.datetime(
year, month, day, hour, minute, second, microsecond
)
return cls.instance(dt, tz)
@classmethod
def create_from_format(cls, time, fmt, tz=UTC, formatter='classic'):
"""
Create a Pendulum instance from a specific format.
:param fmt: The format
:type fmt: str
:param time: The time string
:type time: str
:param tz: The timezone
:type tz: tzinfo or str or int or None
:param formatter: The formatter to use. Default "classic"
:type formatter: str
:rtype: Pendulum
"""
if formatter not in FORMATTERS:
raise ValueError('Invalid formatter [{}]'.format(formatter))
if formatter == 'classic':
warnings.warn(
'Using the classic formatter in from_format() '
'is deprecated and will no longer be possible '
'in version 2.0. Use the alternative formatter instead.',
DeprecationWarning,
stacklevel=2
)
dt = datetime.datetime.strptime(time, fmt)
return cls.instance(dt, tz)
formatter = FORMATTERS['alternative']
parts = formatter.parse(time, fmt)
actual_parts = {}
# If timestamp has been specified
# we use it and don't go any further
if parts['timestamp'] is not None:
return cls.create_from_timestamp(parts['timestamp'])
if parts['quarter'] is not None:
dt = cls.now().start_of('year')
while dt.quarter != parts['quarter']:
dt = dt.add(months=3)
actual_parts['year'] = dt.year
actual_parts['month'] = dt.month
actual_parts['day'] = dt.day
# If the date part has not been specified
# we default to today
if all([parts['year'] is None, parts['month'] is None, parts['day'] is None]):
now = cls.now()
parts['year'] = actual_parts['year'] = now.year
parts['month'] = actual_parts['month'] = now.month
parts['day'] = actual_parts['day'] = now.day
# We replace any not set month/day value
# with the first of each unit
if any([parts['month'] is None, parts['day'] is None]):
for part in ['month', 'day']:
if parts[part] is None and actual_parts.get(part) is None:
actual_parts[part] = 1
for part in ['year', 'month', 'day']:
if parts[part] is not None:
actual_parts[part] = parts[part]
# If any of hour/minute/second/microsecond is not set
# We assume start of corresponding value
for part in ['hour', 'minute', 'second', 'microsecond']:
if parts[part] is None:
actual_parts[part] = 0
else:
actual_parts[part] = parts[part]
if parts['day_of_year'] is not None:
text = '{}-{}'.format(
actual_parts['year'], parts['day_of_year']
)
dt = parse(text)
actual_parts['month'] = dt['month']
actual_parts['day'] = dt['day']
# Meridiem
if parts['meridiem'] is not None:
pass
actual_parts['tz'] = parts['tz'] or tz
return cls.create(**actual_parts)
@classmethod
def create_from_timestamp(cls, timestamp, tz=UTC):
"""
Create a Pendulum instance from a timestamp.
:param timestamp: The timestamp
:type timestamp: int or float
:param tz: The timezone
:type tz: Timezone or TimezoneInfo or str or int or None
:rtype: Pendulum
"""
dt = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=UTC)
instance = cls(
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.microsecond,
dt.tzinfo
)
if tz is not UTC and tz != 'UTC':
instance = instance.in_tz(tz)
return instance
@classmethod
def strptime(cls, time, fmt):
dt = datetime.datetime.strptime(time, fmt)
return cls.instance(dt)
def copy(self):
"""
Get a copy of the instance.
:rtype: Pendulum
"""
return self.instance(self._datetime)
# Getters/Setters
def hour_(self, hour):
return self._setter(hour=hour)
def minute_(self, minute):
return self._setter(minute=minute)
def second_(self, second):
return self._setter(second=second)
def microsecond_(self, microsecond):
return self._setter(microsecond=microsecond)
def _setter(self, **kwargs):
kwargs['tzinfo'] = True
return self._tz.convert(self.replace(**kwargs))
def timezone_(self, tz):
return self.__class__(
self.year, self.month, self.day,
self.hour, self.minute, self.second, self.microsecond,
tz
)
def tz_(self, tz):
return self.timezone_(tz)
def timestamp_(self, timestamp, tz=UTC):
return self.create_from_timestamp(timestamp, tz)
@property
def year(self):
return self._year
@property
def month(self):
return self._month
@property
def day(self):
return self._day
@property
def hour(self):
return self._hour
@property
def minute(self):
return self._minute
@property
def second(self):
return self._second
@property
def microsecond(self):
return self._microsecond
@property
def tzinfo(self):
return self._tzinfo
@property
def fold(self):
return self._fold
def timestamp(self):
if self._timestamp is None:
delta = self._datetime - self._EPOCH
self._timestamp = delta.total_seconds()
return self._timestamp
@property
def float_timestamp(self):
return self.timestamp()
@property
def int_timestamp(self):
if self._int_timestamp is None:
delta = self._datetime - self._EPOCH
self._int_timestamp = delta.days * SECONDS_PER_DAY + delta.seconds
return self._int_timestamp
@property
def offset(self):
return self.get_offset()
@property
def offset_hours(self):
return (self.get_offset()
/ SECONDS_PER_MINUTE
/ MINUTES_PER_HOUR)
@property
def local(self):
return self.offset == self.in_timezone(self._local_timezone()).offset
@property
def utc(self):
return self.offset == 0
@property
def is_dst(self):
return self.tzinfo.is_dst
@property
def timezone(self):
return self.get_timezone()
@property
def tz(self):
return self.get_timezone()
@property
def timezone_name(self):
return self.timezone.name
@property
def age(self):
return self.date().diff(self.now(self._tz).date()).in_years()
def get_timezone(self):
return self._tz
def get_offset(self):
return int(self._tzinfo.offset)
def date(self):
return Date.instance(self._datetime.date())
def time(self):
return Time(self.hour, self.minute, self.second, self.microsecond)
def on(self, year, month, day):
"""
Returns a new instance with the current date set to a different date.
:param year: The year
:type year: int
:param month: The month
:type month: int
:param day: The day
:type day: int
:rtype: Pendulum
"""
return self.replace(
year=int(year), month=int(month), day=int(day)
)
def at(self, hour, minute, second, microsecond=0):
"""
Returns a new instance with the current time to a different time.
:param hour: The hour
:type hour: int
:param minute: The minute
:type minute: int
:param second: The second
:type second: int
:param microsecond: The microsecond
:type microsecond: int
:rtype: Pendulum
"""
return self.replace(
hour=hour, minute=minute, second=second,
microsecond=microsecond
)
def with_date_time(self, year, month, day, hour, minute, second, microsecond=0):
"""
Return a new instance with the date and time set to the given values.
:type year: int
:type month: int
:type day: int
:type hour: int
:type minute: int
:type second: int
:rtype: Pendulum
"""
return self.replace(
year=year, month=month, day=day,
hour=hour, minute=minute, second=second,
microsecond=microsecond
)
def with_time_from_string(self, time):
"""
Returns a new instance with the time set by time string.
:param time: The time string
:type time: str
:rtype: Pendulum
"""
time = time.split(':')
hour = int(time[0])
minute = int(time[1]) if len(time) > 1 else 0
second = int(time[2]) if len(time) > 2 else 0
return self.at(hour, minute, second)
def in_timezone(self, tz):
"""
Set the instance's timezone from a string or object.
:param value: The timezone
:type value: Timezone or TimezoneInfo or str or None
:rtype: Pendulum
"""
tz = self._safe_create_datetime_zone(tz)
return tz.convert(self)
def in_tz(self, tz):
"""
Set the instance's timezone from a string or object.
:param value: The timezone
:type value: Timezone or TimezoneInfo or str or int or None
:rtype: Pendulum
"""
return self.in_timezone(tz)
def with_timestamp(self, timestamp):
"""
Set the date and time based on a Unix timestamp.
:param timestamp: The timestamp
:type timestamp: int or float
:rtype: Pendulum
"""
dt = datetime.datetime.fromtimestamp(timestamp, UTC).astimezone(self._tz)
return self.instance(dt)
# Normalization Rule
@classmethod
def set_transition_rule(cls, rule):
if rule not in [Timezone.PRE_TRANSITION,
Timezone.POST_TRANSITION,
Timezone.TRANSITION_ERROR]:
raise ValueError('Invalid transition rule: {}'.format(rule))
cls._TRANSITION_RULE = rule
@classmethod
def get_transition_rule(cls):
return cls._TRANSITION_RULE
# STRING FORMATTING
def to_time_string(self):
"""
Format the instance as time.
:rtype: str
"""
return self.format('%H:%M:%S', formatter='classic')
def to_datetime_string(self):
"""
Format the instance as date and time.
:rtype: str
"""
return self.format('%Y-%m-%d %H:%M:%S', formatter='classic')
def to_day_datetime_string(self):
"""
Format the instance as day, date and time.
:rtype: str
"""
return self.format('ddd, MMM D, YYYY h:mm A', formatter='alternative')
def to_atom_string(self):
"""
Format the instance as ATOM.
:rtype: str
"""
return self.format(self.ATOM, formatter='classic')
def to_cookie_string(self):
"""
Format the instance as COOKIE.
:rtype: str
"""
return self.format(self.COOKIE, formatter='classic')
def to_iso8601_string(self, extended=False):
"""
Format the instance as ISO8601.
:rtype: str
"""
fmt = self.ISO8601
if extended:
fmt = self.ISO8601_EXTENDED
return self.format(fmt, formatter='classic')
def to_rfc822_string(self):
"""
Format the instance as RFC822.
:rtype: str
"""
return self.format(self.RFC822, formatter='classic')
def to_rfc850_string(self):
"""
Format the instance as RFC850.
:rtype: str
"""
return self.format(self.RFC850, formatter='classic')
def to_rfc1036_string(self):
"""
Format the instance as RFC1036.
:rtype: str
"""
return self.format(self.RFC1036, formatter='classic')
def to_rfc1123_string(self):
"""
Format the instance as RFC1123.
:rtype: str
"""
return self.format(self.RFC1123, formatter='classic')
def to_rfc2822_string(self):
"""
Format the instance as RFC2822.
:rtype: str
"""
return self.format(self.RFC2822, formatter='classic')
def to_rfc3339_string(self, extended=False):
"""
Format the instance as RFC3339.
:rtype: str
"""
fmt = self.RFC3339
if extended:
fmt = self.RFC3339_EXTENDED
return self.format(fmt, formatter='classic')
def to_rss_string(self):
"""
Format the instance as RSS.
:rtype: str
"""
return self.format(self.RSS, formatter='classic')
def to_w3c_string(self):
"""
Format the instance as W3C.
:rtype: str
"""
return self.format(self.W3C, formatter='classic')
# Comparisons
def __eq__(self, other):
try:
return self._datetime == self._get_datetime(other)
except ValueError:
return NotImplemented
def __ne__(self, other):
try:
return self._datetime != self._get_datetime(other)
except ValueError:
return NotImplemented
def __gt__(self, other):
try:
return self._datetime > self._get_datetime(other)
except ValueError:
return NotImplemented
def __ge__(self, other):
try:
return self._datetime >= self._get_datetime(other)
except ValueError:
return NotImplemented
def __lt__(self, other):
try:
return self._datetime < self._get_datetime(other)
except ValueError:
return NotImplemented
def __le__(self, other):
try:
return self._datetime <= self._get_datetime(other)
except ValueError:
return NotImplemented
def between(self, dt1, dt2, equal=True):
"""
Determines if the instance is between two others.
:type dt1: Pendulum or datetime or str or int
:type dt2: Pendulum or datetime or str or int
: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: Pendulum or datetime
:type dt2: Pendulum or datetime
:rtype: Pendulum
"""
dt1 = self._get_datetime(dt1, True)
dt2 = self._get_datetime(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: Pendulum or datetime
:type dt2: Pendulum or datetime
:rtype: Pendulum
"""
dt1 = self._get_datetime(dt1, True)
dt2 = self._get_datetime(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.