-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy pathtslib.pyx
2886 lines (2413 loc) · 92 KB
/
tslib.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
# cython: profile=False
cimport numpy as np
from numpy cimport (int32_t, int64_t, import_array, ndarray,
NPY_INT64, NPY_DATETIME, NPY_TIMEDELTA)
import numpy as np
from cpython cimport (
PyTypeObject,
PyFloat_Check,
PyObject_RichCompareBool,
PyString_Check
)
# Cython < 0.17 doesn't have this in cpython
cdef extern from "Python.h":
cdef PyTypeObject *Py_TYPE(object)
from libc.stdlib cimport free
from util cimport is_integer_object, is_datetime64_object
cimport util
from datetime cimport *
from khash cimport *
cimport cython
from datetime import timedelta, datetime
from datetime import time as datetime_time
from pandas.compat import parse_date
cdef extern from "Python.h":
int PySlice_Check(object)
# initialize numpy
import_array()
#import_ufunc()
# import datetime C API
PyDateTime_IMPORT
# in numpy 1.7, will prob need the following:
# numpy_pydatetime_import
cdef int64_t NPY_NAT = util.get_nat()
try:
basestring
except NameError: # py3
basestring = str
def ints_to_pydatetime(ndarray[int64_t] arr, tz=None):
cdef:
Py_ssize_t i, n = len(arr)
pandas_datetimestruct dts
ndarray[object] result = np.empty(n, dtype=object)
if tz is not None:
if _is_utc(tz):
for i in range(n):
if arr[i] == iNaT:
result[i] = np.nan
else:
pandas_datetime_to_datetimestruct(arr[i], PANDAS_FR_ns, &dts)
result[i] = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
elif _is_tzlocal(tz) or _is_fixed_offset(tz):
for i in range(n):
if arr[i] == iNaT:
result[i] = np.nan
else:
pandas_datetime_to_datetimestruct(arr[i], PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
result[i] = dt + tz.utcoffset(dt)
else:
trans = _get_transitions(tz)
deltas = _get_deltas(tz)
for i in range(n):
if arr[i] == iNaT:
result[i] = np.nan
else:
# Adjust datetime64 timestamp, recompute datetimestruct
pos = trans.searchsorted(arr[i]) - 1
inf = tz._transition_info[pos]
pandas_datetime_to_datetimestruct(arr[i] + deltas[pos],
PANDAS_FR_ns, &dts)
result[i] = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us,
tz._tzinfos[inf])
else:
for i in range(n):
if arr[i] == iNaT:
result[i] = np.nan
else:
pandas_datetime_to_datetimestruct(arr[i], PANDAS_FR_ns, &dts)
result[i] = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us)
return result
from dateutil.tz import tzlocal
def _is_tzlocal(tz):
return isinstance(tz, tzlocal)
def _is_fixed_offset(tz):
try:
tz._transition_info
return False
except AttributeError:
return True
# Python front end to C extension type _Timestamp
# This serves as the box for datetime64
class Timestamp(_Timestamp):
"""TimeStamp is the pandas equivalent of python's Datetime
and is interchangable with it in most cases. It's the type used
for the entries that make up a DatetimeIndex, and other timeseries
oriented data structures in pandas.
"""
@classmethod
def fromordinal(cls, ordinal, offset=None, tz=None):
""" passed an ordinal, translate and convert to a ts
note: by definition there cannot be any tz info on the ordinal itself """
return cls(datetime.fromordinal(ordinal),offset=offset,tz=tz)
def __new__(cls, object ts_input, object offset=None, tz=None, unit=None):
cdef _TSObject ts
cdef _Timestamp ts_base
if util.is_string_object(ts_input):
try:
ts_input = parse_date(ts_input)
except Exception:
pass
ts = convert_to_tsobject(ts_input, tz, unit)
if ts.value == NPY_NAT:
return NaT
# make datetime happy
ts_base = _Timestamp.__new__(cls, ts.dts.year, ts.dts.month,
ts.dts.day, ts.dts.hour, ts.dts.min,
ts.dts.sec, ts.dts.us, ts.tzinfo)
# fill out rest of data
ts_base.value = ts.value
ts_base.offset = offset
ts_base.nanosecond = ts.dts.ps / 1000
return ts_base
def __repr__(self):
result = self._repr_base
zone = None
try:
result += self.strftime('%z')
if self.tzinfo:
zone = _get_zone(self.tzinfo)
except ValueError:
year2000 = self.replace(year=2000)
result += year2000.strftime('%z')
if self.tzinfo:
zone = _get_zone(self.tzinfo)
try:
result += zone.strftime(' %%Z')
except:
pass
zone = "'%s'" % zone if zone else 'None'
return "Timestamp('%s', tz=%s)" % (result,zone)
@property
def _repr_base(self):
result = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (self.year, self.month,
self.day, self.hour,
self.minute, self.second)
if self.nanosecond != 0:
nanos = self.nanosecond + 1000 * self.microsecond
result += '.%.9d' % nanos
elif self.microsecond != 0:
result += '.%.6d' % self.microsecond
return result
@property
def tz(self):
"""
Alias for tzinfo
"""
return self.tzinfo
@property
def freq(self):
return self.offset
def __setstate__(self, state):
self.value = state[0]
self.offset = state[1]
self.tzinfo = state[2]
def __reduce__(self):
object_state = self.value, self.offset, self.tzinfo
return (Timestamp, object_state)
def to_period(self, freq=None):
"""
Return an period of which this timestamp is an observation.
"""
from pandas.tseries.period import Period
if freq is None:
freq = self.freq
return Period(self, freq=freq)
@property
def dayofweek(self):
return self.weekday()
@property
def dayofyear(self):
return self._get_field('doy')
@property
def week(self):
return self._get_field('woy')
weekofyear = week
@property
def quarter(self):
return self._get_field('q')
@property
def freqstr(self):
return getattr(self.offset, 'freqstr', self.offset)
@property
def asm8(self):
return np.int64(self.value).view('M8[ns]')
def tz_localize(self, tz):
"""
Convert naive Timestamp to local time zone
Parameters
----------
tz : pytz.timezone
Returns
-------
localized : Timestamp
"""
if self.tzinfo is None:
# tz naive, localize
return Timestamp(self.to_pydatetime(), tz=tz)
else:
raise Exception('Cannot localize tz-aware Timestamp, use '
'tz_convert for conversions')
def tz_convert(self, tz):
"""
Convert Timestamp to another time zone or localize to requested time
zone
Parameters
----------
tz : pytz.timezone
Returns
-------
converted : Timestamp
"""
if self.tzinfo is None:
# tz naive, use tz_localize
raise Exception('Cannot convert tz-naive Timestamp, use '
'tz_localize to localize')
else:
# Same UTC timestamp, different time zone
return Timestamp(self.value, tz=tz)
astimezone = tz_convert
def replace(self, **kwds):
return Timestamp(datetime.replace(self, **kwds),
offset=self.offset)
def to_pydatetime(self, warn=True):
"""
If warn=True, issue warning if nanoseconds is nonzero
"""
cdef:
pandas_datetimestruct dts
_TSObject ts
if self.nanosecond != 0 and warn:
print 'Warning: discarding nonzero nanoseconds'
ts = convert_to_tsobject(self, self.tzinfo, None)
return datetime(ts.dts.year, ts.dts.month, ts.dts.day,
ts.dts.hour, ts.dts.min, ts.dts.sec,
ts.dts.us, ts.tzinfo)
_nat_strings = set(['NaT','nat','NAT','nan','NaN','NAN'])
_not_datelike_strings = set(['a','A','m','M','p','P','t','T'])
class NaTType(_NaT):
"""(N)ot-(A)-(T)ime, the time equivalent of NaN"""
def __new__(cls):
cdef _NaT base
base = _NaT.__new__(cls, 1, 1, 1)
mangle_nat(base)
base.value = NPY_NAT
return base
def __repr__(self):
return 'NaT'
def weekday(self):
return -1
def toordinal(self):
return -1
fields = ['year', 'quarter', 'month', 'day', 'hour',
'minute', 'second', 'microsecond', 'nanosecond',
'week', 'dayofyear']
for field in fields:
prop = property(fget=lambda self: -1)
setattr(NaTType, field, prop)
NaT = NaTType()
iNaT = util.get_nat()
cdef _tz_format(object obj, object zone):
try:
return obj.strftime(' %%Z, tz=%s' % zone)
except:
return ', tz=%s' % zone
def is_timestamp_array(ndarray[object] values):
cdef int i, n = len(values)
if n == 0:
return False
for i in range(n):
if not is_timestamp(values[i]):
return False
return True
cpdef object get_value_box(ndarray arr, object loc):
cdef:
Py_ssize_t i, sz
void* data_ptr
if util.is_float_object(loc):
casted = int(loc)
if casted == loc:
loc = casted
i = <Py_ssize_t> loc
sz = np.PyArray_SIZE(arr)
if i < 0 and sz > 0:
i += sz
if i >= sz or sz == 0 or i < 0:
raise IndexError('index out of bounds')
if arr.descr.type_num == NPY_DATETIME:
return Timestamp(util.get_value_1d(arr, i))
else:
return util.get_value_1d(arr, i)
# Add the min and max fields at the class level
# These are defined as magic numbers due to strange
# wraparound behavior when using the true int64 lower boundary
cdef int64_t _NS_LOWER_BOUND = -9223285636854775000LL
cdef int64_t _NS_UPPER_BOUND = 9223372036854775807LL
Timestamp.min = Timestamp(_NS_LOWER_BOUND)
Timestamp.max = Timestamp(_NS_UPPER_BOUND)
#----------------------------------------------------------------------
# Frequency inference
def unique_deltas(ndarray[int64_t] arr):
cdef:
Py_ssize_t i, n = len(arr)
int64_t val
khiter_t k
kh_int64_t *table
int ret = 0
list uniques = []
table = kh_init_int64()
kh_resize_int64(table, 10)
for i in range(n - 1):
val = arr[i + 1] - arr[i]
k = kh_get_int64(table, val)
if k == table.n_buckets:
kh_put_int64(table, val, &ret)
uniques.append(val)
kh_destroy_int64(table)
result = np.array(uniques, dtype=np.int64)
result.sort()
return result
cdef inline bint _is_multiple(int64_t us, int64_t mult):
return us % mult == 0
def apply_offset(ndarray[object] values, object offset):
cdef:
Py_ssize_t i, n = len(values)
ndarray[int64_t] new_values
object boxed
result = np.empty(n, dtype='M8[ns]')
new_values = result.view('i8')
pass
# This is PITA. Because we inherit from datetime, which has very specific
# construction requirements, we need to do object instantiation in python
# (see Timestamp class above). This will serve as a C extension type that
# shadows the python class, where we do any heavy lifting.
cdef class _Timestamp(datetime):
cdef readonly:
int64_t value, nanosecond
object offset # frequency reference
def __hash__(self):
if self.nanosecond:
return hash(self.value)
else:
return datetime.__hash__(self)
def __richcmp__(_Timestamp self, object other, int op):
cdef _Timestamp ots
if isinstance(other, _Timestamp):
ots = other
elif type(other) is datetime:
if self.nanosecond == 0:
val = self.to_datetime()
return PyObject_RichCompareBool(val, other, op)
try:
ots = Timestamp(other)
except ValueError:
return self._compare_outside_nanorange(other, op)
else:
if op == 2:
return False
elif op == 3:
return True
else:
raise TypeError('Cannot compare Timestamp with '
'{0!r}'.format(other.__class__.__name__))
self._assert_tzawareness_compat(other)
if op == 2: # ==
return self.value == ots.value
elif op == 3: # !=
return self.value != ots.value
elif op == 0: # <
return self.value < ots.value
elif op == 1: # <=
return self.value <= ots.value
elif op == 4: # >
return self.value > ots.value
elif op == 5: # >=
return self.value >= ots.value
cdef _compare_outside_nanorange(self, object other, int op):
dtval = self.to_datetime()
self._assert_tzawareness_compat(other)
if self.nanosecond == 0:
if op == 2: # ==
return dtval == other
elif op == 3: # !=
return dtval != other
elif op == 0: # <
return dtval < other
elif op == 1: # <=
return dtval <= other
elif op == 4: # >
return dtval > other
elif op == 5: # >=
return dtval >= other
else:
if op == 2: # ==
return False
elif op == 3: # !=
return True
elif op == 0: # <
return dtval < other
elif op == 1: # <=
return dtval < other
elif op == 4: # >
return dtval >= other
elif op == 5: # >=
return dtval >= other
cdef _assert_tzawareness_compat(self, object other):
if self.tzinfo is None:
if other.tzinfo is not None:
raise Exception('Cannot compare tz-naive and '
'tz-aware timestamps')
elif other.tzinfo is None:
raise Exception('Cannot compare tz-naive and tz-aware timestamps')
cpdef to_datetime(self):
cdef:
pandas_datetimestruct dts
_TSObject ts
ts = convert_to_tsobject(self, self.tzinfo, None)
dts = ts.dts
return datetime(dts.year, dts.month, dts.day,
dts.hour, dts.min, dts.sec,
dts.us, ts.tzinfo)
def __add__(self, other):
if is_integer_object(other):
if self.offset is None:
msg = ("Cannot add integral value to Timestamp "
"without offset.")
raise ValueError(msg)
else:
return Timestamp((self.offset.__mul__(other)).apply(self))
else:
if isinstance(other, timedelta) or hasattr(other, 'delta'):
nanos = _delta_to_nanoseconds(other)
return Timestamp(self.value + nanos, tz=self.tzinfo)
else:
result = datetime.__add__(self, other)
if isinstance(result, datetime):
result = Timestamp(result)
result.nanosecond = self.nanosecond
return result
def __sub__(self, other):
if is_integer_object(other):
return self.__add__(-other)
else:
return datetime.__sub__(self, other)
cpdef _get_field(self, field):
out = get_date_field(np.array([self.value], dtype=np.int64), field)
return out[0]
cdef PyTypeObject* ts_type = <PyTypeObject*> Timestamp
cdef inline bint is_timestamp(object o):
return Py_TYPE(o) == ts_type # isinstance(o, Timestamp)
cdef class _NaT(_Timestamp):
def __hash__(_NaT self):
# py3k needs this defined here
return hash(self.value)
def __richcmp__(_NaT self, object other, int op):
# if not isinstance(other, (_NaT, _Timestamp)):
# raise TypeError('Cannot compare %s with NaT' % type(other))
if op == 2: # ==
return False
elif op == 3: # !=
return True
elif op == 0: # <
return False
elif op == 1: # <=
return False
elif op == 4: # >
return False
elif op == 5: # >=
return False
def _delta_to_nanoseconds(delta):
try:
delta = delta.delta
except:
pass
return (delta.days * 24 * 60 * 60 * 1000000
+ delta.seconds * 1000000
+ delta.microseconds) * 1000
# lightweight C object to hold datetime & int64 pair
cdef class _TSObject:
cdef:
pandas_datetimestruct dts # pandas_datetimestruct
int64_t value # numpy dt64
object tzinfo
property value:
def __get__(self):
return self.value
cpdef _get_utcoffset(tzinfo, obj):
try:
return tzinfo._utcoffset
except AttributeError:
return tzinfo.utcoffset(obj)
# helper to extract datetime and int64 from several different possibilities
cdef convert_to_tsobject(object ts, object tz, object unit):
"""
Extract datetime and int64 from any of:
- np.int64 (with unit providing a possible modifier)
- np.datetime64
- a float (with unit providing a possible modifier)
- python int or long object (with unit providing a possible modifier)
- iso8601 string object
- python datetime object
- another timestamp object
"""
cdef:
_TSObject obj
bint utc_convert = 1
if tz is not None:
if isinstance(tz, basestring):
tz = pytz.timezone(tz)
obj = _TSObject()
if ts is None or ts is NaT:
obj.value = NPY_NAT
elif is_datetime64_object(ts):
obj.value = _get_datetime64_nanos(ts)
pandas_datetime_to_datetimestruct(obj.value, PANDAS_FR_ns, &obj.dts)
elif is_integer_object(ts):
if ts == NPY_NAT:
obj.value = NPY_NAT
else:
ts = ts * cast_from_unit(unit,None)
obj.value = ts
pandas_datetime_to_datetimestruct(ts, PANDAS_FR_ns, &obj.dts)
elif util.is_float_object(ts):
if ts != ts or ts == NPY_NAT:
obj.value = NPY_NAT
else:
ts = cast_from_unit(unit,ts)
obj.value = ts
pandas_datetime_to_datetimestruct(ts, PANDAS_FR_ns, &obj.dts)
elif util.is_string_object(ts):
if ts in _nat_strings:
obj.value = NPY_NAT
else:
_string_to_dts(ts, &obj.dts)
obj.value = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &obj.dts)
elif PyDateTime_Check(ts):
if tz is not None:
# sort of a temporary hack
if ts.tzinfo is not None:
if (hasattr(tz, 'normalize') and
hasattr(ts.tzinfo, '_utcoffset')):
ts = tz.normalize(ts)
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = ts.tzinfo
else: #tzoffset
obj.value = _pydatetime_to_dts(ts, &obj.dts)
ts_offset = _get_utcoffset(ts.tzinfo, ts)
obj.value -= _delta_to_nanoseconds(ts_offset)
tz_offset = _get_utcoffset(tz, ts)
obj.value += _delta_to_nanoseconds(tz_offset)
pandas_datetime_to_datetimestruct(obj.value,
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz
elif not _is_utc(tz):
try:
ts = tz.localize(ts)
except AttributeError:
ts = ts.replace(tzinfo=tz)
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = ts.tzinfo
else:
# UTC
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = pytz.utc
else:
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = ts.tzinfo
if obj.tzinfo is not None and not _is_utc(obj.tzinfo):
offset = _get_utcoffset(obj.tzinfo, ts)
obj.value -= _delta_to_nanoseconds(offset)
if is_timestamp(ts):
obj.value += ts.nanosecond
_check_dts_bounds(obj.value, &obj.dts)
return obj
elif PyDate_Check(ts):
# Keep the converter same as PyDateTime's
ts = datetime.combine(ts, datetime_time())
return convert_to_tsobject(ts, tz, None)
else:
raise ValueError("Could not construct Timestamp from argument %s" %
type(ts))
if obj.value != NPY_NAT:
_check_dts_bounds(obj.value, &obj.dts)
if tz is not None:
_localize_tso(obj, tz)
return obj
cdef inline void _localize_tso(_TSObject obj, object tz):
if _is_utc(tz):
obj.tzinfo = tz
elif _is_tzlocal(tz):
pandas_datetime_to_datetimestruct(obj.value, PANDAS_FR_ns, &obj.dts)
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day, obj.dts.hour,
obj.dts.min, obj.dts.sec, obj.dts.us, tz)
delta = int(total_seconds(_get_utcoffset(tz, dt))) * 1000000000
pandas_datetime_to_datetimestruct(obj.value + delta,
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz
else:
# Adjust datetime64 timestamp, recompute datetimestruct
trans = _get_transitions(tz)
deltas = _get_deltas(tz)
pos = trans.searchsorted(obj.value, side='right') - 1
# statictzinfo
if not hasattr(tz, '_transition_info'):
pandas_datetime_to_datetimestruct(obj.value + deltas[0],
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz
else:
inf = tz._transition_info[pos]
pandas_datetime_to_datetimestruct(obj.value + deltas[pos],
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz._tzinfos[inf]
def get_timezone(tz):
return _get_zone(tz)
cdef inline bint _is_utc(object tz):
return tz is UTC or isinstance(tz, _du_utc)
cdef inline object _get_zone(object tz):
if _is_utc(tz):
return 'UTC'
else:
try:
zone = tz.zone
if zone is None:
return tz
return zone
except AttributeError:
return tz
cdef inline _check_dts_bounds(int64_t value, pandas_datetimestruct *dts):
cdef pandas_datetimestruct dts2
if dts.year <= 1677 or dts.year >= 2262:
pandas_datetime_to_datetimestruct(value, PANDAS_FR_ns, &dts2)
if dts2.year != dts.year:
fmt = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, dts.month,
dts.day, dts.hour,
dts.min, dts.sec)
raise ValueError('Out of bounds nanosecond timestamp: %s' % fmt)
# elif isinstance(ts, _Timestamp):
# tmp = ts
# obj.value = (<_Timestamp> ts).value
# obj.dtval =
# elif isinstance(ts, object):
# # If all else fails
# obj.value = _dtlike_to_datetime64(ts, &obj.dts)
# obj.dtval = _dts_to_pydatetime(&obj.dts)
def datetime_to_datetime64(ndarray[object] values):
cdef:
Py_ssize_t i, n = len(values)
object val, inferred_tz = None
ndarray[int64_t] iresult
pandas_datetimestruct dts
_TSObject _ts
result = np.empty(n, dtype='M8[ns]')
iresult = result.view('i8')
for i in range(n):
val = values[i]
if util._checknull(val):
iresult[i] = iNaT
elif PyDateTime_Check(val):
if val.tzinfo is not None:
if inferred_tz is not None:
if _get_zone(val.tzinfo) != inferred_tz:
raise ValueError('Array must be all same time zone')
else:
inferred_tz = _get_zone(val.tzinfo)
_ts = convert_to_tsobject(val, None, None)
iresult[i] = _ts.value
_check_dts_bounds(iresult[i], &_ts.dts)
else:
if inferred_tz is not None:
raise ValueError('Cannot mix tz-aware with tz-naive values')
iresult[i] = _pydatetime_to_dts(val, &dts)
_check_dts_bounds(iresult[i], &dts)
else:
raise TypeError('Unrecognized value type: %s' % type(val))
return result, inferred_tz
def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
format=None, utc=None, coerce=False, unit=None):
cdef:
Py_ssize_t i, n = len(values)
object val
ndarray[int64_t] iresult
ndarray[object] oresult
pandas_datetimestruct dts
bint utc_convert = bool(utc)
_TSObject _ts
int64_t m = cast_from_unit(unit,None)
try:
result = np.empty(n, dtype='M8[ns]')
iresult = result.view('i8')
for i in range(n):
val = values[i]
if util._checknull(val) or val is NaT:
iresult[i] = iNaT
elif PyDateTime_Check(val):
if val.tzinfo is not None:
if utc_convert:
_ts = convert_to_tsobject(val, None, unit)
iresult[i] = _ts.value
_check_dts_bounds(iresult[i], &_ts.dts)
else:
raise ValueError('Tz-aware datetime.datetime cannot '
'be converted to datetime64 unless '
'utc=True')
else:
iresult[i] = _pydatetime_to_dts(val, &dts)
if is_timestamp(val):
iresult[i] += (<_Timestamp>val).nanosecond
_check_dts_bounds(iresult[i], &dts)
elif PyDate_Check(val):
iresult[i] = _date_to_datetime64(val, &dts)
_check_dts_bounds(iresult[i], &dts)
elif util.is_datetime64_object(val):
iresult[i] = _get_datetime64_nanos(val)
# if we are coercing, dont' allow integers
elif util.is_integer_object(val) and not coerce:
if val == iNaT:
iresult[i] = iNaT
else:
iresult[i] = val*m
elif util.is_float_object(val) and not coerce:
if val != val or val == iNaT:
iresult[i] = iNaT
else:
iresult[i] = cast_from_unit(unit,val)
else:
try:
if len(val) == 0:
iresult[i] = iNaT
continue
elif val in _nat_strings:
iresult[i] = iNaT
continue
_string_to_dts(val, &dts)
iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns,
&dts)
_check_dts_bounds(iresult[i], &dts)
except ValueError:
# for some reason, dateutil parses some single letter len-1 strings into today's date
if len(val) == 1 and val in _not_datelike_strings:
if coerce:
iresult[i] = iNaT
continue
elif raise_:
raise
try:
result[i] = parse_date(val, dayfirst=dayfirst)
except Exception:
if coerce:
iresult[i] = iNaT
continue
raise TypeError
pandas_datetime_to_datetimestruct(iresult[i], PANDAS_FR_ns,
&dts)
_check_dts_bounds(iresult[i], &dts)
except:
if coerce:
iresult[i] = iNaT
continue
raise
return result
except TypeError:
oresult = np.empty(n, dtype=object)
for i in range(n):
val = values[i]
if util._checknull(val):
oresult[i] = val
else:
if len(val) == 0:
# TODO: ??
oresult[i] = 'NaT'
continue
try:
oresult[i] = parse_date(val, dayfirst=dayfirst)
except Exception:
if raise_:
raise
return values
# oresult[i] = val
return oresult
def array_to_timedelta64(ndarray[object] values, coerce=True):
""" convert an ndarray to an array of ints that are timedeltas
force conversion if coerce = True,
else return an object array """
cdef:
Py_ssize_t i, n
object val
ndarray[int64_t] result
n = values.shape[0]
result = np.empty(n, dtype='i8')
for i in range(n):
val = values[i]
# in py3 this is already an int, don't convert
if is_integer_object(val):
result[i] = val
elif isinstance(val,timedelta) or isinstance(val,np.timedelta64):
if isinstance(val, np.timedelta64):
if val.dtype != 'm8[ns]':
val = val.astype('m8[ns]')
val = val.item()
else:
val = _delta_to_nanoseconds(np.timedelta64(val).item())
result[i] = val
elif util._checknull(val) or val == iNaT or val is NaT:
result[i] = iNaT
else:
# just return, don't convert
if not coerce:
return values.copy()
result[i] = iNaT
return result
def repr_timedelta64(object value):
""" provide repr for timedelta64 """