forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtimestamps.pyx
2389 lines (1933 loc) · 74.3 KB
/
timestamps.pyx
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
"""
_Timestamp is a c-defined subclass of datetime.datetime
_Timestamp is PITA. Because we inherit from datetime, which has very specific
construction requirements, we need to do object instantiation in python
(see Timestamp class below). This will serve as a C extension type that
shadows the python class, where we do any heavy lifting.
"""
import warnings
cimport cython
import numpy as np
cimport numpy as cnp
from numpy cimport (
int64_t,
ndarray,
uint8_t,
)
cnp.import_array()
from cpython.datetime cimport ( # alias bc `tzinfo` is a kwarg below
PyDate_Check,
PyDateTime_Check,
PyDelta_Check,
PyTZInfo_Check,
datetime,
import_datetime,
time as dt_time,
tzinfo as tzinfo_type,
)
from cpython.object cimport (
Py_EQ,
Py_GE,
Py_GT,
Py_LE,
Py_LT,
Py_NE,
PyObject_RichCompare,
PyObject_RichCompareBool,
)
import_datetime()
from pandas._libs.tslibs cimport ccalendar
from pandas._libs.tslibs.base cimport ABCTimestamp
from pandas.util._exceptions import find_stack_level
from pandas._libs.tslibs.conversion cimport (
_TSObject,
convert_datetime_to_tsobject,
convert_to_tsobject,
maybe_localize_tso,
)
from pandas._libs.tslibs.dtypes cimport (
npy_unit_to_abbrev,
periods_per_day,
periods_per_second,
)
from pandas._libs.tslibs.util cimport (
is_array,
is_datetime64_object,
is_integer_object,
)
from pandas._libs.tslibs.fields import (
RoundTo,
get_date_name_field,
get_start_end_field,
round_nsint64,
)
from pandas._libs.tslibs.nattype cimport (
NPY_NAT,
c_NaT as NaT,
)
from pandas._libs.tslibs.np_datetime cimport (
NPY_DATETIMEUNIT,
NPY_FR_ns,
check_dts_bounds,
cmp_dtstructs,
cmp_scalar,
convert_reso,
get_datetime64_unit,
get_datetime64_value,
get_unit_from_dtype,
import_pandas_datetime,
npy_datetimestruct,
npy_datetimestruct_to_datetime,
pandas_datetime_to_datetimestruct,
pydatetime_to_dtstruct,
)
import_pandas_datetime()
from pandas._libs.tslibs.np_datetime import (
OutOfBoundsDatetime,
OutOfBoundsTimedelta,
)
from pandas._libs.tslibs.offsets cimport to_offset
from pandas._libs.tslibs.timedeltas cimport (
_Timedelta,
delta_to_nanoseconds,
is_any_td_scalar,
)
from pandas._libs.tslibs.timedeltas import Timedelta
from pandas._libs.tslibs.timezones cimport (
get_timezone,
is_utc,
maybe_get_tz,
treat_tz_as_pytz,
utc_stdlib as UTC,
)
from pandas._libs.tslibs.tzconversion cimport (
tz_convert_from_utc_single,
tz_localize_to_utc_single,
)
# ----------------------------------------------------------------------
# Constants
_zero_time = dt_time(0, 0)
_no_input = object()
# ----------------------------------------------------------------------
cdef _Timestamp create_timestamp_from_ts(
int64_t value,
npy_datetimestruct dts,
tzinfo tz,
bint fold,
NPY_DATETIMEUNIT reso=NPY_FR_ns,
):
""" convenience routine to construct a Timestamp from its parts """
cdef:
_Timestamp ts_base
int64_t pass_year = dts.year
# We pass year=1970/1972 here and set year below because with non-nanosecond
# resolution we may have datetimes outside of the stdlib pydatetime
# implementation bounds, which would raise.
# NB: this means the C-API macro PyDateTime_GET_YEAR is unreliable.
if 1 <= pass_year <= 9999:
# we are in-bounds for pydatetime
pass
elif ccalendar.is_leapyear(dts.year):
pass_year = 1972
else:
pass_year = 1970
ts_base = _Timestamp.__new__(Timestamp, pass_year, dts.month,
dts.day, dts.hour, dts.min,
dts.sec, dts.us, tz, fold=fold)
ts_base._value = value
ts_base.year = dts.year
ts_base.nanosecond = dts.ps // 1000
ts_base._creso = reso
return ts_base
def _unpickle_timestamp(value, freq, tz, reso=NPY_FR_ns):
# GH#41949 dont warn on unpickle if we have a freq
ts = Timestamp._from_value_and_reso(value, reso, tz)
return ts
# ----------------------------------------------------------------------
def integer_op_not_supported(obj):
# GH#22535 add/sub of integers and int-arrays is no longer allowed
# Note we return rather than raise the exception so we can raise in
# the caller; mypy finds this more palatable.
cls = type(obj).__name__
# GH#30886 using an fstring raises SystemError
int_addsub_msg = (
f"Addition/subtraction of integers and integer-arrays with {cls} is "
"no longer supported. Instead of adding/subtracting `n`, "
"use `n * obj.freq`"
)
return TypeError(int_addsub_msg)
class MinMaxReso:
"""
We need to define min/max/resolution on both the Timestamp _instance_
and Timestamp class. On an instance, these depend on the object's _reso.
On the class, we default to the values we would get with nanosecond _reso.
See also: timedeltas.MinMaxReso
"""
def __init__(self, name):
self._name = name
def __get__(self, obj, type=None):
cls = Timestamp
if self._name == "min":
val = np.iinfo(np.int64).min + 1
elif self._name == "max":
val = np.iinfo(np.int64).max
else:
assert self._name == "resolution"
val = 1
cls = Timedelta
if obj is None:
# i.e. this is on the class, default to nanos
return cls(val)
elif self._name == "resolution":
return Timedelta._from_value_and_reso(val, obj._creso)
else:
return Timestamp._from_value_and_reso(val, obj._creso, tz=None)
def __set__(self, obj, value):
raise AttributeError(f"{self._name} is not settable.")
# ----------------------------------------------------------------------
cdef class _Timestamp(ABCTimestamp):
# higher than np.ndarray and np.matrix
__array_priority__ = 100
dayofweek = _Timestamp.day_of_week
dayofyear = _Timestamp.day_of_year
min = MinMaxReso("min")
max = MinMaxReso("max")
resolution = MinMaxReso("resolution") # GH#21336, GH#21365
@property
def value(self) -> int:
try:
return convert_reso(self._value, self._creso, NPY_FR_ns, False)
except OverflowError:
raise OverflowError(
"Cannot convert Timestamp to nanoseconds without overflow. "
"Use `.asm8.view('i8')` to cast represent Timestamp in its own "
f"unit (here, {self.unit})."
)
@property
def unit(self) -> str:
"""
The abbreviation associated with self._creso.
Examples
--------
>>> pd.Timestamp("2020-01-01 12:34:56").unit
's'
>>> pd.Timestamp("2020-01-01 12:34:56.123").unit
'ms'
>>> pd.Timestamp("2020-01-01 12:34:56.123456").unit
'us'
>>> pd.Timestamp("2020-01-01 12:34:56.123456789").unit
'ns'
"""
return npy_unit_to_abbrev(self._creso)
# -----------------------------------------------------------------
# Constructors
@classmethod
def _from_value_and_reso(cls, int64_t value, NPY_DATETIMEUNIT reso, tzinfo tz):
cdef:
_TSObject obj = _TSObject()
if value == NPY_NAT:
return NaT
if reso < NPY_DATETIMEUNIT.NPY_FR_s or reso > NPY_DATETIMEUNIT.NPY_FR_ns:
raise NotImplementedError(
"Only resolutions 's', 'ms', 'us', 'ns' are supported."
)
obj.value = value
obj.creso = reso
pandas_datetime_to_datetimestruct(value, reso, &obj.dts)
maybe_localize_tso(obj, tz, reso)
return create_timestamp_from_ts(
value, obj.dts, tz=obj.tzinfo, fold=obj.fold, reso=reso
)
@classmethod
def _from_dt64(cls, dt64: np.datetime64):
# construct a Timestamp from a np.datetime64 object, keeping the
# resolution of the input.
# This is herely mainly so we can incrementally implement non-nano
# (e.g. only tznaive at first)
cdef:
int64_t value
NPY_DATETIMEUNIT reso
reso = get_datetime64_unit(dt64)
value = get_datetime64_value(dt64)
return cls._from_value_and_reso(value, reso, None)
# -----------------------------------------------------------------
def __hash__(_Timestamp self):
if self.nanosecond:
return hash(self._value)
if not (1 <= self.year <= 9999):
# out of bounds for pydatetime
return hash(self._value)
if self.fold:
return datetime.__hash__(self.replace(fold=0))
return datetime.__hash__(self)
def __richcmp__(_Timestamp self, object other, int op):
cdef:
_Timestamp ots
if isinstance(other, _Timestamp):
ots = other
elif other is NaT:
return op == Py_NE
elif is_datetime64_object(other):
ots = Timestamp(other)
elif PyDateTime_Check(other):
if self.nanosecond == 0:
val = self.to_pydatetime()
return PyObject_RichCompareBool(val, other, op)
try:
ots = type(self)(other)
except ValueError:
return self._compare_outside_nanorange(other, op)
elif is_array(other):
# avoid recursion error GH#15183
if other.dtype.kind == "M":
if self.tz is None:
return PyObject_RichCompare(self.asm8, other, op)
elif op == Py_NE:
return np.ones(other.shape, dtype=np.bool_)
elif op == Py_EQ:
return np.zeros(other.shape, dtype=np.bool_)
raise TypeError(
"Cannot compare tz-naive and tz-aware timestamps"
)
elif other.dtype.kind == "O":
# Operate element-wise
return np.array(
[PyObject_RichCompare(self, x, op) for x in other],
dtype=bool,
)
elif op == Py_NE:
return np.ones(other.shape, dtype=np.bool_)
elif op == Py_EQ:
return np.zeros(other.shape, dtype=np.bool_)
return NotImplemented
elif PyDate_Check(other):
# returning NotImplemented defers to the `date` implementation
# which incorrectly drops tz and normalizes to midnight
# before comparing
# We follow the stdlib datetime behavior of never being equal
if op == Py_EQ:
return False
elif op == Py_NE:
return True
raise TypeError(
"Cannot compare Timestamp with datetime.date. "
"Use ts == pd.Timestamp(date) or ts.date() == date instead."
)
else:
return NotImplemented
if not self._can_compare(ots):
if op == Py_NE or op == Py_EQ:
return NotImplemented
raise TypeError(
"Cannot compare tz-naive and tz-aware timestamps"
)
if self._creso == ots._creso:
return cmp_scalar(self._value, ots._value, op)
return self._compare_mismatched_resos(ots, op)
# TODO: copied from Timedelta; try to de-duplicate
cdef bint _compare_mismatched_resos(self, _Timestamp other, int op):
# Can't just dispatch to numpy as they silently overflow and get it wrong
cdef:
npy_datetimestruct dts_self
npy_datetimestruct dts_other
# dispatch to the datetimestruct utils instead of writing new ones!
pandas_datetime_to_datetimestruct(self._value, self._creso, &dts_self)
pandas_datetime_to_datetimestruct(other._value, other._creso, &dts_other)
return cmp_dtstructs(&dts_self, &dts_other, op)
cdef bint _compare_outside_nanorange(_Timestamp self, datetime other,
int op) except -1:
cdef:
datetime dtval = self.to_pydatetime(warn=False)
if not self._can_compare(other):
return NotImplemented
if self.nanosecond == 0:
return PyObject_RichCompareBool(dtval, other, op)
# otherwise we have dtval < self
if op == Py_NE:
return True
if op == Py_EQ:
return False
if op == Py_LE or op == Py_LT:
return self.year <= other.year
if op == Py_GE or op == Py_GT:
return self.year >= other.year
cdef bint _can_compare(self, datetime other):
if self.tzinfo is not None:
return other.tzinfo is not None
return other.tzinfo is None
@cython.overflowcheck(True)
def __add__(self, other):
cdef:
int64_t nanos = 0
if is_any_td_scalar(other):
other = Timedelta(other)
# TODO: share this with __sub__, Timedelta.__add__
# Matching numpy, we cast to the higher resolution. Unlike numpy,
# we raise instead of silently overflowing during this casting.
if self._creso < other._creso:
self = (<_Timestamp>self)._as_creso(other._creso, round_ok=True)
elif self._creso > other._creso:
other = (<_Timedelta>other)._as_creso(self._creso, round_ok=True)
nanos = other._value
try:
new_value = self._value+ nanos
result = type(self)._from_value_and_reso(
new_value, reso=self._creso, tz=self.tzinfo
)
except OverflowError as err:
# TODO: don't hard-code nanosecond here
new_value = int(self._value) + int(nanos)
raise OutOfBoundsDatetime(
f"Out of bounds nanosecond timestamp: {new_value}"
) from err
return result
elif is_integer_object(other):
raise integer_op_not_supported(self)
elif is_array(other):
if other.dtype.kind in ["i", "u"]:
raise integer_op_not_supported(self)
if other.dtype.kind == "m":
if self.tz is None:
return self.asm8 + other
return np.asarray(
[self + other[n] for n in range(len(other))],
dtype=object,
)
elif not isinstance(self, _Timestamp):
# cython semantics, args have been switched and this is __radd__
# TODO(cython3): remove this it moved to __radd__
return other.__add__(self)
return NotImplemented
def __radd__(self, other):
# Have to duplicate checks to avoid infinite recursion due to NotImplemented
if is_any_td_scalar(other) or is_integer_object(other) or is_array(other):
return self.__add__(other)
return NotImplemented
def __sub__(self, other):
if other is NaT:
return NaT
elif is_any_td_scalar(other) or is_integer_object(other):
neg_other = -other
return self + neg_other
elif is_array(other):
if other.dtype.kind in ["i", "u"]:
raise integer_op_not_supported(self)
if other.dtype.kind == "m":
if self.tz is None:
return self.asm8 - other
return np.asarray(
[self - other[n] for n in range(len(other))],
dtype=object,
)
return NotImplemented
# coerce if necessary if we are a Timestamp-like
if (PyDateTime_Check(self)
and (PyDateTime_Check(other) or is_datetime64_object(other))):
# both_timestamps is to determine whether Timedelta(self - other)
# should raise the OOB error, or fall back returning a timedelta.
# TODO(cython3): clean out the bits that moved to __rsub__
both_timestamps = (isinstance(other, _Timestamp) and
isinstance(self, _Timestamp))
if isinstance(self, _Timestamp):
other = type(self)(other)
else:
self = type(other)(self)
if (self.tzinfo is None) ^ (other.tzinfo is None):
raise TypeError(
"Cannot subtract tz-naive and tz-aware datetime-like objects."
)
# Matching numpy, we cast to the higher resolution. Unlike numpy,
# we raise instead of silently overflowing during this casting.
if self._creso < other._creso:
self = (<_Timestamp>self)._as_creso(other._creso, round_ok=True)
elif self._creso > other._creso:
other = (<_Timestamp>other)._as_creso(self._creso, round_ok=True)
# scalar Timestamp/datetime - Timestamp/datetime -> yields a
# Timedelta
try:
res_value = self._value- other._value
return Timedelta._from_value_and_reso(res_value, self._creso)
except (OverflowError, OutOfBoundsDatetime, OutOfBoundsTimedelta) as err:
if isinstance(other, _Timestamp):
if both_timestamps:
raise OutOfBoundsDatetime(
"Result is too large for pandas.Timedelta. Convert inputs "
"to datetime.datetime with 'Timestamp.to_pydatetime()' "
"before subtracting."
) from err
# We get here in stata tests, fall back to stdlib datetime
# method and return stdlib timedelta object
pass
elif is_datetime64_object(self):
# GH#28286 cython semantics for __rsub__, `other` is actually
# the Timestamp
# TODO(cython3): remove this, this moved to __rsub__
return type(other)(self) - other
return NotImplemented
def __rsub__(self, other):
if PyDateTime_Check(other):
try:
return type(self)(other) - self
except (OverflowError, OutOfBoundsDatetime) as err:
# We get here in stata tests, fall back to stdlib datetime
# method and return stdlib timedelta object
pass
elif is_datetime64_object(other):
return type(self)(other) - self
return NotImplemented
# -----------------------------------------------------------------
cdef int64_t _maybe_convert_value_to_local(self):
"""Convert UTC i8 value to local i8 value if tz exists"""
cdef:
int64_t val
tzinfo own_tz = self.tzinfo
npy_datetimestruct dts
if own_tz is not None and not is_utc(own_tz):
pydatetime_to_dtstruct(self, &dts)
val = npy_datetimestruct_to_datetime(self._creso, &dts) + self.nanosecond
else:
val = self._value
return val
@cython.boundscheck(False)
cdef bint _get_start_end_field(self, str field, freq):
cdef:
int64_t val
dict kwds
ndarray[uint8_t, cast=True] out
int month_kw
if freq:
kwds = freq.kwds
month_kw = kwds.get("startingMonth", kwds.get("month", 12))
freqstr = freq.freqstr
else:
month_kw = 12
freqstr = None
val = self._maybe_convert_value_to_local()
out = get_start_end_field(np.array([val], dtype=np.int64),
field, freqstr, month_kw, self._creso)
return out[0]
@property
def is_month_start(self) -> bool:
"""
Check if the date is the first day of the month.
Returns
-------
bool
True if the date is the first day of the month.
See Also
--------
Timestamp.is_month_end : Similar property indicating the last day of the month.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_month_start
False
>>> ts = pd.Timestamp(2020, 1, 1)
>>> ts.is_month_start
True
"""
return self.day == 1
@property
def is_month_end(self) -> bool:
"""
Check if the date is the last day of the month.
Returns
-------
bool
True if the date is the last day of the month.
See Also
--------
Timestamp.is_month_start : Similar property indicating month start.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_month_end
False
>>> ts = pd.Timestamp(2020, 12, 31)
>>> ts.is_month_end
True
"""
return self.day == self.days_in_month
@property
def is_quarter_start(self) -> bool:
"""
Check if the date is the first day of the quarter.
Returns
-------
bool
True if date is first day of the quarter.
See Also
--------
Timestamp.is_quarter_end : Similar property indicating the quarter end.
Timestamp.quarter : Return the quarter of the date.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_quarter_start
False
>>> ts = pd.Timestamp(2020, 4, 1)
>>> ts.is_quarter_start
True
"""
return self.day == 1 and self.month % 3 == 1
@property
def is_quarter_end(self) -> bool:
"""
Check if date is last day of the quarter.
Returns
-------
bool
True if date is last day of the quarter.
See Also
--------
Timestamp.is_quarter_start : Similar property indicating the quarter start.
Timestamp.quarter : Return the quarter of the date.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_quarter_end
False
>>> ts = pd.Timestamp(2020, 3, 31)
>>> ts.is_quarter_end
True
"""
return (self.month % 3) == 0 and self.day == self.days_in_month
@property
def is_year_start(self) -> bool:
"""
Return True if date is first day of the year.
Returns
-------
bool
See Also
--------
Timestamp.is_year_end : Similar property indicating the end of the year.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_year_start
False
>>> ts = pd.Timestamp(2020, 1, 1)
>>> ts.is_year_start
True
"""
return self.day == self.month == 1
@property
def is_year_end(self) -> bool:
"""
Return True if date is last day of the year.
Returns
-------
bool
See Also
--------
Timestamp.is_year_start : Similar property indicating the start of the year.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_year_end
False
>>> ts = pd.Timestamp(2020, 12, 31)
>>> ts.is_year_end
True
"""
return self.month == 12 and self.day == 31
@cython.boundscheck(False)
cdef _get_date_name_field(self, str field, object locale):
cdef:
int64_t val
object[::1] out
val = self._maybe_convert_value_to_local()
out = get_date_name_field(np.array([val], dtype=np.int64),
field, locale=locale, reso=self._creso)
return out[0]
def day_name(self, locale=None) -> str:
"""
Return the day name of the Timestamp with specified locale.
Parameters
----------
locale : str, default None (English locale)
Locale determining the language in which to return the day name.
Returns
-------
str
Examples
--------
>>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651')
>>> ts.day_name()
'Saturday'
Analogous for ``pd.NaT``:
>>> pd.NaT.day_name()
nan
"""
return self._get_date_name_field("day_name", locale)
def month_name(self, locale=None) -> str:
"""
Return the month name of the Timestamp with specified locale.
Parameters
----------
locale : str, default None (English locale)
Locale determining the language in which to return the month name.
Returns
-------
str
Examples
--------
>>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651')
>>> ts.month_name()
'March'
Analogous for ``pd.NaT``:
>>> pd.NaT.month_name()
nan
"""
return self._get_date_name_field("month_name", locale)
@property
def is_leap_year(self) -> bool:
"""
Return True if year is a leap year.
Returns
-------
bool
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.is_leap_year
True
"""
return bool(ccalendar.is_leapyear(self.year))
@property
def day_of_week(self) -> int:
"""
Return day of the week.
Returns
-------
int
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.day_of_week
5
"""
return self.weekday()
@property
def day_of_year(self) -> int:
"""
Return the day of the year.
Returns
-------
int
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.day_of_year
74
"""
return ccalendar.get_day_of_year(self.year, self.month, self.day)
@property
def quarter(self) -> int:
"""
Return the quarter of the year.
Returns
-------
int
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.quarter
1
"""
return ((self.month - 1) // 3) + 1
@property
def week(self) -> int:
"""
Return the week number of the year.
Returns
-------
int
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.week
11
"""
return ccalendar.get_week_of_year(self.year, self.month, self.day)
@property
def days_in_month(self) -> int:
"""
Return the number of days in the month.
Returns
-------
int
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14)
>>> ts.days_in_month
31
"""
return ccalendar.get_days_in_month(self.year, self.month)
# -----------------------------------------------------------------
# Transformation Methods
def normalize(self) -> "Timestamp":
"""
Normalize Timestamp to midnight, preserving tz information.
Examples
--------
>>> ts = pd.Timestamp(2020, 3, 14, 15, 30)
>>> ts.normalize()
Timestamp('2020-03-14 00:00:00')
"""
cdef:
local_val = self._maybe_convert_value_to_local()
int64_t normalized
int64_t ppd = periods_per_day(self._creso)
_Timestamp ts
normalized = normalize_i8_stamp(local_val, ppd)
ts = type(self)._from_value_and_reso(normalized, reso=self._creso, tz=None)
return ts.tz_localize(self.tzinfo)
# -----------------------------------------------------------------
# Pickle Methods
def __reduce_ex__(self, protocol):
# python 3.6 compat
# https://bugs.python.org/issue28730
# now __reduce_ex__ is defined and higher priority than __reduce__
return self.__reduce__()
def __setstate__(self, state):
self._value= state[0]
self.tzinfo = state[2]
if len(state) == 3:
# pre-non-nano pickle
# TODO: no tests get here 2022-05-10
reso = NPY_FR_ns
else:
reso = state[4]
self._creso = reso
def __reduce__(self):
object_state = self._value, None, self.tzinfo, self._creso
return (_unpickle_timestamp, object_state)
# -----------------------------------------------------------------
# Rendering Methods
def isoformat(self, sep: str = "T", timespec: str = "auto") -> str:
"""
Return the time formatted according to ISO 8601.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmmnnn'.
By default, the fractional part is omitted if self.microsecond == 0
and self.nanosecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmmnnn+HH:MM'.
Parameters
----------
sep : str, default 'T'
String used as the separator between the date and time.
timespec : str, default 'auto'
Specifies the number of additional terms of the time to include.
The valid values are 'auto', 'hours', 'minutes', 'seconds',