-
-
Notifications
You must be signed in to change notification settings - Fork 683
/
arrow.py
1886 lines (1409 loc) · 62.1 KB
/
arrow.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
"""
Provides the :class:`Arrow <arrow.arrow.Arrow>` class, an enhanced ``datetime``
replacement.
"""
import calendar
import re
import sys
from datetime import date
from datetime import datetime as dt_datetime
from datetime import time as dt_time
from datetime import timedelta
from datetime import tzinfo as dt_tzinfo
from math import trunc
from time import struct_time
from typing import (
Any,
ClassVar,
Generator,
Iterable,
List,
Mapping,
Optional,
Tuple,
Union,
cast,
overload,
)
from dateutil import tz as dateutil_tz
from dateutil.relativedelta import relativedelta
from arrow import formatter, locales, parser, util
from arrow.constants import DEFAULT_LOCALE, DEHUMANIZE_LOCALES
from arrow.locales import TimeFrameLiteral
if sys.version_info < (3, 8): # pragma: no cover
from typing_extensions import Final, Literal
else:
from typing import Final, Literal # pragma: no cover
TZ_EXPR = Union[dt_tzinfo, str]
_T_FRAMES = Literal[
"year",
"years",
"month",
"months",
"day",
"days",
"hour",
"hours",
"minute",
"minutes",
"second",
"seconds",
"microsecond",
"microseconds",
"week",
"weeks",
"quarter",
"quarters",
]
_BOUNDS = Literal["[)", "()", "(]", "[]"]
_GRANULARITY = Literal[
"auto",
"second",
"minute",
"hour",
"day",
"week",
"month",
"quarter",
"year",
]
class Arrow:
"""An :class:`Arrow <arrow.arrow.Arrow>` object.
Implements the ``datetime`` interface, behaving as an aware ``datetime`` while implementing
additional functionality.
:param year: the calendar year.
:param month: the calendar month.
:param day: the calendar day.
:param hour: (optional) the hour. Defaults to 0.
:param minute: (optional) the minute, Defaults to 0.
:param second: (optional) the second, Defaults to 0.
:param microsecond: (optional) the microsecond. Defaults to 0.
:param tzinfo: (optional) A timezone expression. Defaults to UTC.
:param fold: (optional) 0 or 1, used to disambiguate repeated wall times. Defaults to 0.
.. _tz-expr:
Recognized timezone expressions:
- A ``tzinfo`` object.
- A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'.
- A ``str`` in ISO 8601 style, as in '+07:00'.
- A ``str``, one of the following: 'local', 'utc', 'UTC'.
Usage::
>>> import arrow
>>> arrow.Arrow(2013, 5, 5, 12, 30, 45)
<Arrow [2013-05-05T12:30:45+00:00]>
"""
resolution: ClassVar[timedelta] = dt_datetime.resolution
min: ClassVar["Arrow"]
max: ClassVar["Arrow"]
_ATTRS: Final[List[str]] = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"microsecond",
]
_ATTRS_PLURAL: Final[List[str]] = [f"{a}s" for a in _ATTRS]
_MONTHS_PER_QUARTER: Final[int] = 3
_SECS_PER_MINUTE: Final[int] = 60
_SECS_PER_HOUR: Final[int] = 60 * 60
_SECS_PER_DAY: Final[int] = 60 * 60 * 24
_SECS_PER_WEEK: Final[int] = 60 * 60 * 24 * 7
_SECS_PER_MONTH: Final[float] = 60 * 60 * 24 * 30.5
_SECS_PER_QUARTER: Final[float] = 60 * 60 * 24 * 30.5 * 3
_SECS_PER_YEAR: Final[int] = 60 * 60 * 24 * 365
_SECS_MAP: Final[Mapping[TimeFrameLiteral, float]] = {
"second": 1.0,
"minute": _SECS_PER_MINUTE,
"hour": _SECS_PER_HOUR,
"day": _SECS_PER_DAY,
"week": _SECS_PER_WEEK,
"month": _SECS_PER_MONTH,
"quarter": _SECS_PER_QUARTER,
"year": _SECS_PER_YEAR,
}
_datetime: dt_datetime
def __init__(
self,
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tzinfo: Optional[TZ_EXPR] = None,
**kwargs: Any,
) -> None:
if tzinfo is None:
tzinfo = dateutil_tz.tzutc()
# detect that tzinfo is a pytz object (issue #626)
elif (
isinstance(tzinfo, dt_tzinfo)
and hasattr(tzinfo, "localize")
and hasattr(tzinfo, "zone")
and tzinfo.zone # type: ignore[attr-defined]
):
tzinfo = parser.TzinfoParser.parse(tzinfo.zone) # type: ignore[attr-defined]
elif isinstance(tzinfo, str):
tzinfo = parser.TzinfoParser.parse(tzinfo)
fold = kwargs.get("fold", 0)
self._datetime = dt_datetime(
year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold
)
# factories: single object, both original and from datetime.
@classmethod
def now(cls, tzinfo: Optional[dt_tzinfo] = None) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in the given
timezone.
:param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time.
Usage::
>>> arrow.now('Asia/Baku')
<Arrow [2019-01-24T20:26:31.146412+04:00]>
"""
if tzinfo is None:
tzinfo = dateutil_tz.tzlocal()
dt = dt_datetime.now(tzinfo)
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
dt.tzinfo,
fold=getattr(dt, "fold", 0),
)
@classmethod
def utcnow(cls) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in UTC
time.
Usage::
>>> arrow.utcnow()
<Arrow [2019-01-24T16:31:40.651108+00:00]>
"""
dt = dt_datetime.now(dateutil_tz.tzutc())
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
dt.tzinfo,
fold=getattr(dt, "fold", 0),
)
@classmethod
def fromtimestamp(
cls,
timestamp: Union[int, float, str],
tzinfo: Optional[TZ_EXPR] = None,
) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, converted to
the given timezone.
:param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either.
:param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time.
"""
if tzinfo is None:
tzinfo = dateutil_tz.tzlocal()
elif isinstance(tzinfo, str):
tzinfo = parser.TzinfoParser.parse(tzinfo)
if not util.is_timestamp(timestamp):
raise ValueError(f"The provided timestamp {timestamp!r} is invalid.")
timestamp = util.normalize_timestamp(float(timestamp))
dt = dt_datetime.fromtimestamp(timestamp, tzinfo)
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
dt.tzinfo,
fold=getattr(dt, "fold", 0),
)
@classmethod
def utcfromtimestamp(cls, timestamp: Union[int, float, str]) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, in UTC time.
:param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either.
"""
if not util.is_timestamp(timestamp):
raise ValueError(f"The provided timestamp {timestamp!r} is invalid.")
timestamp = util.normalize_timestamp(float(timestamp))
dt = dt_datetime.utcfromtimestamp(timestamp)
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
dateutil_tz.tzutc(),
fold=getattr(dt, "fold", 0),
)
@classmethod
def fromdatetime(cls, dt: dt_datetime, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``datetime`` and
optional replacement timezone.
:param dt: the ``datetime``
:param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to ``dt``'s
timezone, or UTC if naive.
Usage::
>>> dt
datetime.datetime(2021, 4, 7, 13, 48, tzinfo=tzfile('/usr/share/zoneinfo/US/Pacific'))
>>> arrow.Arrow.fromdatetime(dt)
<Arrow [2021-04-07T13:48:00-07:00]>
"""
if tzinfo is None:
if dt.tzinfo is None:
tzinfo = dateutil_tz.tzutc()
else:
tzinfo = dt.tzinfo
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
tzinfo,
fold=getattr(dt, "fold", 0),
)
@classmethod
def fromdate(cls, date: date, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``date`` and optional
replacement timezone. All time values are set to 0.
:param date: the ``date``
:param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to UTC.
"""
if tzinfo is None:
tzinfo = dateutil_tz.tzutc()
return cls(date.year, date.month, date.day, tzinfo=tzinfo)
@classmethod
def strptime(
cls, date_str: str, fmt: str, tzinfo: Optional[TZ_EXPR] = None
) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a date string and format,
in the style of ``datetime.strptime``. Optionally replaces the parsed timezone.
:param date_str: the date string.
:param fmt: the format string using datetime format codes.
:param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to the parsed
timezone if ``fmt`` contains a timezone directive, otherwise UTC.
Usage::
>>> arrow.Arrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S')
<Arrow [2019-01-20T15:49:10+00:00]>
"""
dt = dt_datetime.strptime(date_str, fmt)
if tzinfo is None:
tzinfo = dt.tzinfo
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
tzinfo,
fold=getattr(dt, "fold", 0),
)
@classmethod
def fromordinal(cls, ordinal: int) -> "Arrow":
"""Constructs an :class:`Arrow <arrow.arrow.Arrow>` object corresponding
to the Gregorian Ordinal.
:param ordinal: an ``int`` corresponding to a Gregorian Ordinal.
Usage::
>>> arrow.fromordinal(737741)
<Arrow [2020-11-12T00:00:00+00:00]>
"""
util.validate_ordinal(ordinal)
dt = dt_datetime.fromordinal(ordinal)
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
dt.tzinfo,
fold=getattr(dt, "fold", 0),
)
# factories: ranges and spans
@classmethod
def range(
cls,
frame: _T_FRAMES,
start: Union["Arrow", dt_datetime],
end: Union["Arrow", dt_datetime, None] = None,
tz: Optional[TZ_EXPR] = None,
limit: Optional[int] = None,
) -> Generator["Arrow", None, None]:
"""Returns an iterator of :class:`Arrow <arrow.arrow.Arrow>` objects, representing
points in time between two inputs.
:param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...).
:param start: A datetime expression, the start of the range.
:param end: (optional) A datetime expression, the end of the range.
:param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to
``start``'s timezone, or UTC if ``start`` is naive.
:param limit: (optional) A maximum number of tuples to return.
**NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to
return the entire range. Call with ``limit`` alone to return a maximum # of results from
the start. Call with both to cap a range at a maximum # of results.
**NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before
iterating. As such, either call with naive objects and ``tz``, or aware objects from the
same timezone and no ``tz``.
Supported frame values: year, quarter, month, week, day, hour, minute, second, microsecond.
Recognized datetime expressions:
- An :class:`Arrow <arrow.arrow.Arrow>` object.
- A ``datetime`` object.
Usage::
>>> start = datetime(2013, 5, 5, 12, 30)
>>> end = datetime(2013, 5, 5, 17, 15)
>>> for r in arrow.Arrow.range('hour', start, end):
... print(repr(r))
...
<Arrow [2013-05-05T12:30:00+00:00]>
<Arrow [2013-05-05T13:30:00+00:00]>
<Arrow [2013-05-05T14:30:00+00:00]>
<Arrow [2013-05-05T15:30:00+00:00]>
<Arrow [2013-05-05T16:30:00+00:00]>
**NOTE**: Unlike Python's ``range``, ``end`` *may* be included in the returned iterator::
>>> start = datetime(2013, 5, 5, 12, 30)
>>> end = datetime(2013, 5, 5, 13, 30)
>>> for r in arrow.Arrow.range('hour', start, end):
... print(repr(r))
...
<Arrow [2013-05-05T12:30:00+00:00]>
<Arrow [2013-05-05T13:30:00+00:00]>
"""
_, frame_relative, relative_steps = cls._get_frames(frame)
tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz)
start = cls._get_datetime(start).replace(tzinfo=tzinfo)
end, limit = cls._get_iteration_params(end, limit)
end = cls._get_datetime(end).replace(tzinfo=tzinfo)
current = cls.fromdatetime(start)
original_day = start.day
day_is_clipped = False
i = 0
while current <= end and i < limit:
i += 1
yield current
values = [getattr(current, f) for f in cls._ATTRS]
current = cls(*values, tzinfo=tzinfo).shift( # type: ignore
**{frame_relative: relative_steps}
)
if frame in ["month", "quarter", "year"] and current.day < original_day:
day_is_clipped = True
if day_is_clipped and not cls._is_last_day_of_month(current):
current = current.replace(day=original_day)
def span(
self,
frame: _T_FRAMES,
count: int = 1,
bounds: _BOUNDS = "[)",
exact: bool = False,
week_start: int = 1,
) -> Tuple["Arrow", "Arrow"]:
"""Returns a tuple of two new :class:`Arrow <arrow.arrow.Arrow>` objects, representing the timespan
of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe.
:param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...).
:param count: (optional) the number of frames to span.
:param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies
whether to include or exclude the start and end values in the span. '(' excludes
the start, '[' includes the start, ')' excludes the end, and ']' includes the end.
If the bounds are not specified, the default bound '[)' is used.
:param exact: (optional) whether to have the start of the timespan begin exactly
at the time specified by ``start`` and the end of the timespan truncated
so as not to extend beyond ``end``.
:param week_start: (optional) only used in combination with the week timeframe. Follows isoweekday() where
Monday is 1 and Sunday is 7.
Supported frame values: year, quarter, month, week, day, hour, minute, second.
Usage::
>>> arrow.utcnow()
<Arrow [2013-05-09T03:32:36.186203+00:00]>
>>> arrow.utcnow().span('hour')
(<Arrow [2013-05-09T03:00:00+00:00]>, <Arrow [2013-05-09T03:59:59.999999+00:00]>)
>>> arrow.utcnow().span('day')
(<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-09T23:59:59.999999+00:00]>)
>>> arrow.utcnow().span('day', count=2)
(<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-10T23:59:59.999999+00:00]>)
>>> arrow.utcnow().span('day', bounds='[]')
(<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-10T00:00:00+00:00]>)
>>> arrow.utcnow().span('week')
(<Arrow [2021-02-22T00:00:00+00:00]>, <Arrow [2021-02-28T23:59:59.999999+00:00]>)
>>> arrow.utcnow().span('week', week_start=6)
(<Arrow [2021-02-20T00:00:00+00:00]>, <Arrow [2021-02-26T23:59:59.999999+00:00]>)
"""
if not 1 <= week_start <= 7:
raise ValueError("week_start argument must be between 1 and 7.")
util.validate_bounds(bounds)
frame_absolute, frame_relative, relative_steps = self._get_frames(frame)
if frame_absolute == "week":
attr = "day"
elif frame_absolute == "quarter":
attr = "month"
else:
attr = frame_absolute
floor = self
if not exact:
index = self._ATTRS.index(attr)
frames = self._ATTRS[: index + 1]
values = [getattr(self, f) for f in frames]
for _ in range(3 - len(values)):
values.append(1)
floor = self.__class__(*values, tzinfo=self.tzinfo) # type: ignore
if frame_absolute == "week":
# if week_start is greater than self.isoweekday() go back one week by setting delta = 7
delta = 7 if week_start > self.isoweekday() else 0
floor = floor.shift(days=-(self.isoweekday() - week_start) - delta)
elif frame_absolute == "quarter":
floor = floor.shift(months=-((self.month - 1) % 3))
ceil = floor.shift(**{frame_relative: count * relative_steps})
if bounds[0] == "(":
floor = floor.shift(microseconds=+1)
if bounds[1] == ")":
ceil = ceil.shift(microseconds=-1)
return floor, ceil
def floor(self, frame: _T_FRAMES) -> "Arrow":
"""Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "floor"
of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe.
Equivalent to the first element in the 2-tuple returned by
:func:`span <arrow.arrow.Arrow.span>`.
:param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...).
Usage::
>>> arrow.utcnow().floor('hour')
<Arrow [2013-05-09T03:00:00+00:00]>
"""
return self.span(frame)[0]
def ceil(self, frame: _T_FRAMES) -> "Arrow":
"""Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "ceiling"
of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe.
Equivalent to the second element in the 2-tuple returned by
:func:`span <arrow.arrow.Arrow.span>`.
:param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...).
Usage::
>>> arrow.utcnow().ceil('hour')
<Arrow [2013-05-09T03:59:59.999999+00:00]>
"""
return self.span(frame)[1]
@classmethod
def span_range(
cls,
frame: _T_FRAMES,
start: dt_datetime,
end: dt_datetime,
tz: Optional[TZ_EXPR] = None,
limit: Optional[int] = None,
bounds: _BOUNDS = "[)",
exact: bool = False,
) -> Iterable[Tuple["Arrow", "Arrow"]]:
"""Returns an iterator of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects,
representing a series of timespans between two inputs.
:param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...).
:param start: A datetime expression, the start of the range.
:param end: (optional) A datetime expression, the end of the range.
:param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to
``start``'s timezone, or UTC if ``start`` is naive.
:param limit: (optional) A maximum number of tuples to return.
:param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies
whether to include or exclude the start and end values in each span in the range. '(' excludes
the start, '[' includes the start, ')' excludes the end, and ']' includes the end.
If the bounds are not specified, the default bound '[)' is used.
:param exact: (optional) whether to have the first timespan start exactly
at the time specified by ``start`` and the final span truncated
so as not to extend beyond ``end``.
**NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to
return the entire range. Call with ``limit`` alone to return a maximum # of results from
the start. Call with both to cap a range at a maximum # of results.
**NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before
iterating. As such, either call with naive objects and ``tz``, or aware objects from the
same timezone and no ``tz``.
Supported frame values: year, quarter, month, week, day, hour, minute, second, microsecond.
Recognized datetime expressions:
- An :class:`Arrow <arrow.arrow.Arrow>` object.
- A ``datetime`` object.
**NOTE**: Unlike Python's ``range``, ``end`` will *always* be included in the returned
iterator of timespans.
Usage:
>>> start = datetime(2013, 5, 5, 12, 30)
>>> end = datetime(2013, 5, 5, 17, 15)
>>> for r in arrow.Arrow.span_range('hour', start, end):
... print(r)
...
(<Arrow [2013-05-05T12:00:00+00:00]>, <Arrow [2013-05-05T12:59:59.999999+00:00]>)
(<Arrow [2013-05-05T13:00:00+00:00]>, <Arrow [2013-05-05T13:59:59.999999+00:00]>)
(<Arrow [2013-05-05T14:00:00+00:00]>, <Arrow [2013-05-05T14:59:59.999999+00:00]>)
(<Arrow [2013-05-05T15:00:00+00:00]>, <Arrow [2013-05-05T15:59:59.999999+00:00]>)
(<Arrow [2013-05-05T16:00:00+00:00]>, <Arrow [2013-05-05T16:59:59.999999+00:00]>)
(<Arrow [2013-05-05T17:00:00+00:00]>, <Arrow [2013-05-05T17:59:59.999999+00:00]>)
"""
tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz)
start = cls.fromdatetime(start, tzinfo).span(frame, exact=exact)[0]
end = cls.fromdatetime(end, tzinfo)
_range = cls.range(frame, start, end, tz, limit)
if not exact:
for r in _range:
yield r.span(frame, bounds=bounds, exact=exact)
for r in _range:
floor, ceil = r.span(frame, bounds=bounds, exact=exact)
if ceil > end:
ceil = end
if bounds[1] == ")":
ceil += relativedelta(microseconds=-1)
if floor == end:
break
elif floor + relativedelta(microseconds=-1) == end:
break
yield floor, ceil
@classmethod
def interval(
cls,
frame: _T_FRAMES,
start: dt_datetime,
end: dt_datetime,
interval: int = 1,
tz: Optional[TZ_EXPR] = None,
bounds: _BOUNDS = "[)",
exact: bool = False,
) -> Iterable[Tuple["Arrow", "Arrow"]]:
"""Returns an iterator of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects,
representing a series of intervals between two inputs.
:param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...).
:param start: A datetime expression, the start of the range.
:param end: (optional) A datetime expression, the end of the range.
:param interval: (optional) Time interval for the given time frame.
:param tz: (optional) A timezone expression. Defaults to UTC.
:param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies
whether to include or exclude the start and end values in the intervals. '(' excludes
the start, '[' includes the start, ')' excludes the end, and ']' includes the end.
If the bounds are not specified, the default bound '[)' is used.
:param exact: (optional) whether to have the first timespan start exactly
at the time specified by ``start`` and the final interval truncated
so as not to extend beyond ``end``.
Supported frame values: year, quarter, month, week, day, hour, minute, second
Recognized datetime expressions:
- An :class:`Arrow <arrow.arrow.Arrow>` object.
- A ``datetime`` object.
Recognized timezone expressions:
- A ``tzinfo`` object.
- A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'.
- A ``str`` in ISO 8601 style, as in '+07:00'.
- A ``str``, one of the following: 'local', 'utc', 'UTC'.
Usage:
>>> start = datetime(2013, 5, 5, 12, 30)
>>> end = datetime(2013, 5, 5, 17, 15)
>>> for r in arrow.Arrow.interval('hour', start, end, 2):
... print(r)
...
(<Arrow [2013-05-05T12:00:00+00:00]>, <Arrow [2013-05-05T13:59:59.999999+00:00]>)
(<Arrow [2013-05-05T14:00:00+00:00]>, <Arrow [2013-05-05T15:59:59.999999+00:00]>)
(<Arrow [2013-05-05T16:00:00+00:00]>, <Arrow [2013-05-05T17:59:59.999999+00:0]>)
"""
if interval < 1:
raise ValueError("interval has to be a positive integer")
spanRange = iter(
cls.span_range(frame, start, end, tz, bounds=bounds, exact=exact)
)
while True:
try:
intvlStart, intvlEnd = next(spanRange)
for _ in range(interval - 1):
try:
_, intvlEnd = next(spanRange)
except StopIteration:
continue
yield intvlStart, intvlEnd
except StopIteration:
return
# representations
def __repr__(self) -> str:
return f"<{self.__class__.__name__} [{self.__str__()}]>"
def __str__(self) -> str:
return self._datetime.isoformat()
def __format__(self, formatstr: str) -> str:
if len(formatstr) > 0:
return self.format(formatstr)
return str(self)
def __hash__(self) -> int:
return self._datetime.__hash__()
# attributes and properties
def __getattr__(self, name: str) -> int:
if name == "week":
return self.isocalendar()[1]
if name == "quarter":
return int((self.month - 1) / self._MONTHS_PER_QUARTER) + 1
if not name.startswith("_"):
value: Optional[int] = getattr(self._datetime, name, None)
if value is not None:
return value
return cast(int, object.__getattribute__(self, name))
@property
def tzinfo(self) -> dt_tzinfo:
"""Gets the ``tzinfo`` of the :class:`Arrow <arrow.arrow.Arrow>` object.
Usage::
>>> arw=arrow.utcnow()
>>> arw.tzinfo
tzutc()
"""
# In Arrow, `_datetime` cannot be naive.
return cast(dt_tzinfo, self._datetime.tzinfo)
@property
def datetime(self) -> dt_datetime:
"""Returns a datetime representation of the :class:`Arrow <arrow.arrow.Arrow>` object.
Usage::
>>> arw=arrow.utcnow()
>>> arw.datetime
datetime.datetime(2019, 1, 24, 16, 35, 27, 276649, tzinfo=tzutc())
"""
return self._datetime
@property
def naive(self) -> dt_datetime:
"""Returns a naive datetime representation of the :class:`Arrow <arrow.arrow.Arrow>`
object.
Usage::
>>> nairobi = arrow.now('Africa/Nairobi')
>>> nairobi
<Arrow [2019-01-23T19:27:12.297999+03:00]>
>>> nairobi.naive
datetime.datetime(2019, 1, 23, 19, 27, 12, 297999)
"""
return self._datetime.replace(tzinfo=None)
def timestamp(self) -> float:
"""Returns a timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in
UTC time.
Usage::
>>> arrow.utcnow().timestamp()
1616882340.256501
"""
return self._datetime.timestamp()
@property
def int_timestamp(self) -> int:
"""Returns an integer timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in
UTC time.
Usage::
>>> arrow.utcnow().int_timestamp
1548260567
"""
return int(self.timestamp())
@property
def float_timestamp(self) -> float:
"""Returns a floating-point timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>`
object, in UTC time.
Usage::
>>> arrow.utcnow().float_timestamp
1548260516.830896
"""
return self.timestamp()
@property
def fold(self) -> int:
"""Returns the ``fold`` value of the :class:`Arrow <arrow.arrow.Arrow>` object."""
return self._datetime.fold
@property
def ambiguous(self) -> bool:
"""Indicates whether the :class:`Arrow <arrow.arrow.Arrow>` object is a repeated wall time in the current
timezone.
"""
return dateutil_tz.datetime_ambiguous(self._datetime)
@property
def imaginary(self) -> bool:
"""Indicates whether the :class: `Arrow <arrow.arrow.Arrow>` object exists in the current timezone."""
return not dateutil_tz.datetime_exists(self._datetime)
# mutation and duplication.
def clone(self) -> "Arrow":
"""Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, cloned from the current one.
Usage:
>>> arw = arrow.utcnow()
>>> cloned = arw.clone()
"""
return self.fromdatetime(self._datetime)
def replace(self, **kwargs: Any) -> "Arrow":
"""Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated
according to inputs.
Use property names to set their value absolutely::
>>> import arrow
>>> arw = arrow.utcnow()
>>> arw
<Arrow [2013-05-11T22:27:34.787885+00:00]>
>>> arw.replace(year=2014, month=6)
<Arrow [2014-06-11T22:27:34.787885+00:00]>
You can also replace the timezone without conversion, using a
:ref:`timezone expression <tz-expr>`::
>>> arw.replace(tzinfo=tz.tzlocal())
<Arrow [2013-05-11T22:27:34.787885-07:00]>
"""
absolute_kwargs = {}
for key, value in kwargs.items():
if key in self._ATTRS:
absolute_kwargs[key] = value
elif key in ["week", "quarter"]:
raise ValueError(f"Setting absolute {key} is not supported.")
elif key not in ["tzinfo", "fold"]:
raise ValueError(f"Unknown attribute: {key!r}.")
current = self._datetime.replace(**absolute_kwargs)
tzinfo = kwargs.get("tzinfo")
if tzinfo is not None:
tzinfo = self._get_tzinfo(tzinfo)
current = current.replace(tzinfo=tzinfo)
fold = kwargs.get("fold")
if fold is not None:
current = current.replace(fold=fold)
return self.fromdatetime(current)
def shift(self, **kwargs: Any) -> "Arrow":
"""Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated
according to inputs.
Use pluralized property names to relatively shift their current value:
>>> import arrow
>>> arw = arrow.utcnow()
>>> arw
<Arrow [2013-05-11T22:27:34.787885+00:00]>