-
Notifications
You must be signed in to change notification settings - Fork 39
/
_cftime.pyx
2080 lines (1834 loc) · 88 KB
/
_cftime.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
"""
Performs conversions of netCDF time coordinate data to/from datetime objects.
"""
from cpython.object cimport (PyObject_RichCompare, Py_LT, Py_LE, Py_EQ,
Py_NE, Py_GT, Py_GE)
from numpy cimport int64_t, int32_t
import cython
import numpy as np
import re
import sys
import time
from datetime import datetime as datetime_python
from datetime import timedelta, MINYEAR, MAXYEAR
import time # strftime
import warnings
microsec_units = ['microseconds','microsecond', 'microsec', 'microsecs']
millisec_units = ['milliseconds', 'millisecond', 'millisec', 'millisecs', 'msec', 'msecs', 'ms']
sec_units = ['second', 'seconds', 'sec', 'secs', 's']
min_units = ['minute', 'minutes', 'min', 'mins']
hr_units = ['hour', 'hours', 'hr', 'hrs', 'h']
day_units = ['day', 'days', 'd']
month_units = ['month', 'months'] # only allowed for 360_day calendar
year_units = ['common_year', 'common_years'] # only allowed for 365_day and noleap calendars
_units = microsec_units+millisec_units+sec_units+min_units+hr_units+day_units
# supported calendars. Includes synonyms ('standard'=='gregorian',
# '366_day'=='all_leap','365_day'=='noleap')
# see https://cfconventions.org/cf-conventions/cf-conventions#calendar
# for definitions.
_calendars = ['standard', 'gregorian', 'proleptic_gregorian',
'noleap', 'julian', 'all_leap', '365_day', '366_day', '360_day']
_idealized_calendars= ['all_leap','noleap','366_day','365_day','360_day']
# Following are number of days per month
cdef int[12] _dayspermonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
cdef int[12] _dayspermonth_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# same as above, but including accumulated days of previous months.
cdef int[13] _cumdayspermonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
cdef int[13] _cumdayspermonth_leap = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
__version__ = '1.6.1'
# Adapted from https://delete.me.uk/2005/03/iso8601.html
# Note: This regex ensures that all ISO8601 timezone formats are accepted - but, due to legacy support for other timestrings, not all incorrect formats can be rejected.
# For example, the TZ spec "+01:0" will still work even though the minutes value is only one character long.
ISO8601_REGEX = re.compile(r"(?P<year>[+-]?[0-9]+)(-(?P<month>[0-9]{1,2})(-(?P<day>[0-9]{1,2})"
r"(((?P<separator1>.)(?P<hour>[0-9]{1,2}):(?P<minute>[0-9]{1,2})(:(?P<second>[0-9]{1,2})(\.(?P<fraction>[0-9]+))?)?)?"
r"((?P<separator2>.?)(?P<timezone>Z|(([-+])([0-9]{2})((:([0-9]{2}))|([0-9]{2}))?)))?)?)?)?"
)
# Note: The re module apparently does not support branch reset groups that allow redefinition of the same group name in alternative branches as PCRE does.
# Using two different group names is also somewhat ugly, but other solutions might hugely inflate the expression. feel free to contribute a better solution.
TIMEZONE_REGEX = re.compile(
"(?P<prefix>[+-])(?P<hours>[0-9]{2})(?:(?::(?P<minutes1>[0-9]{2}))|(?P<minutes2>[0-9]{2}))?")
class real_datetime(datetime_python):
"""add dayofwk, dayofyr, daysinmonth attributes to python datetime instance"""
@property
def dayofwk(self):
# 0=Monday, 6=Sunday
return self.weekday()
@property
def dayofyr(self):
return self.timetuple().tm_yday
@property
def daysinmonth(self):
if _is_leap(self.year,'proleptic_gregorian'):
return _dayspermonth_leap[self.month-1]
else:
return _dayspermonth[self.month-1]
nanosecond = 0 # workaround for pandas bug (cftime issue #77)
def _datesplit(timestr):
"""split a time string into two components, units and the remainder
after 'since'
"""
try:
(units, sincestring, remainder) = timestr.split(None,2)
except ValueError as e:
raise ValueError('Incorrectly formatted CF date-time unit_string')
if sincestring.lower() != 'since':
raise ValueError("no 'since' in unit_string")
return units.lower(), remainder
def _dateparse(timestr,calendar,has_year_zero=None):
"""parse a string of the form time-units since yyyy-mm-dd hh:mm:ss,
return a datetime instance"""
# same as version in cftime, but returns a timezone naive
# python datetime instance with the utc_offset included.
calendar = calendar.lower()
# set calendar-specific defaults for has_year_zero
if has_year_zero is None:
has_year_zero = _year_zero_defaults(calendar)
(units, isostring) = _datesplit(timestr)
if not ((units in month_units and calendar=='360_day') or (units in year_units and calendar in {'365_day', 'noleap'}) or units in _units):
if units in month_units and calendar != '360_day':
raise ValueError("'months since' units only allowed for '360_day' calendar")
if units in year_units and calendar not in {'365_day', 'noleap'}:
raise ValueError("'%s' units only allowed for '365_day' and 'noleap' calendars" % units)
else:
raise ValueError(
"In general, units must be one of 'microseconds', 'milliseconds', "
"'seconds', 'minutes', 'hours', or 'days' (or select abbreviated "
"versions of these). For the '360_day' calendar, "
"'months' can also be used, or for the 'noleap' calendar 'common_years' "
"can also be used. Got '%s' instead, which are not recognized." % units)
# parse the date string.
year, month, day, hour, minute, second, microsecond, utc_offset =\
_parse_date( isostring.strip() )
if year == 0 and not has_year_zero and calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
msg='zero not allowed as a reference year when has_year_zero=False'
raise ValueError(msg)
if calendar in ['noleap', '365_day'] and month == 2 and day == 29:
raise ValueError(
'cannot specify a leap day as the reference time with the noleap calendar')
if calendar == '360_day' and day > 30:
raise ValueError(
'there are only 30 days in every month with the 360_day calendar')
basedate = datetime(year, month, day, hour, minute, second,
microsecond,calendar=calendar,has_year_zero=has_year_zero)
# subtract utc_offset from basedate time instance (which is timezone naive)
if utc_offset:
basedate -= timedelta(days=utc_offset/1440.)
return basedate
def _can_use_python_datetime(date,calendar):
gregorian = datetime(1582,10,15,calendar=calendar,has_year_zero=date.has_year_zero)
return ((calendar == 'proleptic_gregorian' and date.year >= MINYEAR and date.year <= MAXYEAR) or \
(calendar in ['gregorian','standard'] and date > gregorian and date.year <= MAXYEAR))
@cython.embedsignature(True)
def date2num(dates, units, calendar=None, has_year_zero=None, longdouble=False):
"""
Return numeric time values given datetime objects. The units
of the numeric time values are described by the **units** argument
and the **calendar** keyword. The datetime objects must
be in UTC with no time-zone offset. If there is a
time-zone offset in **units**, it will be applied to the
returned numeric values.
**dates**: A datetime object or a sequence of datetime objects.
The datetime objects should not include a time-zone offset. They
can be either native python datetime instances (which use
the proleptic gregorian calendar) or cftime.datetime instances.
**units**: a string of the form **<time units> since <reference time>**
describing the time units. **<time units>** can be days, hours, minutes,
seconds, milliseconds or microseconds. **<reference time>** is the time
origin. **months since** is allowed *only* for the **360_day** calendar
and **common_years since** is allowed *only* for the **365_day** calendar.
**calendar**: describes the calendar to be used in the time calculations.
All the values currently defined in the
`CF metadata convention <https://cfconventions.org/cf-conventions/cf-conventions#calendar>`__ are supported.
Valid calendars **'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'**.
Default is `None` which means the calendar associated with the first
input datetime instance will be used.
**has_year_zero**: If set to True, astronomical year numbering
is used and the year zero exists. If set to False for real-world
calendars, then historical year numbering is used and the year 1 is
preceded by year -1 and no year zero exists.
The defaults are set to conform with
CF version 1.9 conventions (False for 'julian', 'gregorian'/'standard', True
for 'proleptic_gregorian' (ISO 8601) and True for the idealized
calendars 'noleap'/'365_day', '360_day', 366_day'/'all_leap')
Note that CF v1.9 does not specifically mention whether year zero
is allowed in the proleptic_gregorian calendar, but ISO-8601 has
a year zero so we have adopted this as the default.
The defaults can only be over-ridden for the real-world calendars,
for the the idealized calendars the year zero
always exists and the has_year_zero kwarg is ignored.
This kwarg is not needed to define calendar systems allowed by CF
(the calendar-specific defaults do this).
**longdouble**: If set True, output is in the long double float type
(numpy.float128) instead of float (numpy.float64), allowing microsecond
accuracy when converting a time value to a date and back again. Otherwise
this is only possible if the discretization of the time variable is an
integer multiple of the units.
returns a numeric time value, or an array of numeric time values
with approximately 1 microsecond accuracy.
"""
# input a scale or array-like?
isscalar = False
try:
dates[0]
except:
isscalar = True
# masked array input?
ismasked = False
if np.ma.isMA(dates) and np.ma.is_masked(dates):
mask = dates.mask
ismasked = True
# are all input dates 'real' python datetime objects?
dates = np.asanyarray(dates) # convert to numpy array
shape = dates.shape # save shape of input
all_python_datetimes = True
for date in dates.flat:
if not isinstance(date,datetime_python):
all_python_datetimes = False
break
# if has_year_zero is None and calendar is None, use first input cftime.datetime instance
# to determine if year zero is to be included.
# If calendar is specified, use calendar specific defaults
if has_year_zero is None:
if calendar is None:
d0 = dates.item(0)
if isinstance(d0,datetime_python):
has_year_zero = False
else:
try:
has_year_zero = d0.has_year_zero
except AttributeError:
raise ValueError('has_year_zero not specified',type(d0))
else:
has_year_zero = _year_zero_defaults(calendar)
# if calendar is None or '', use calendar of first input cftime.datetime instances.
# if inputs are 'real' python datetime instances, use propleptic gregorian.
if not calendar:
if all_python_datetimes:
calendar = 'proleptic_gregorian'
else:
d0 = dates.item(0)
if isinstance(d0,datetime_python):
calendar = 'proleptic_gregorian'
else:
try:
calendar = d0.calendar
except AttributeError:
raise ValueError('no calendar specified',type(d0))
calendar = calendar.lower()
basedate = _dateparse(units,calendar=calendar,has_year_zero=has_year_zero)
(unit, isostring) = _datesplit(units)
# real-world calendars cannot have zero as a reference year.
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian'] and not has_year_zero:
if basedate.year == 0:
msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
raise ValueError(msg)
if unit not in UNIT_CONVERSION_FACTORS:
raise ValueError("Unsupported time units provided, {!r}.".format(unit))
if unit in ["months", "month"] and calendar != "360_day":
raise ValueError("Units of months only valid for 360_day calendar.")
unit_timedelta = timedelta(microseconds=UNIT_CONVERSION_FACTORS[unit])
can_use_python_basedatetime = _can_use_python_datetime(basedate,calendar)
if can_use_python_basedatetime and all_python_datetimes:
use_python_datetime = True
if not isinstance(basedate, datetime_python):
basedate = real_datetime(basedate.year, basedate.month, basedate.day,
basedate.hour, basedate.minute, basedate.second,
basedate.microsecond)
else:
use_python_datetime = False
# convert basedate to specified calendar
basedate = to_calendar_specific_datetime(basedate, calendar, False, has_year_zero=has_year_zero)
times = []
for n, date in enumerate(dates.flat):
if ismasked and mask.flat[n]:
times.append(None)
continue
# use python datetime if possible.
if use_python_datetime:
# remove time zone offset
if getattr(date, 'tzinfo',None) is not None:
date = date.replace(tzinfo=None) - date.utcoffset()
else: # convert date to same calendar specific cftime.datetime instance
date = to_calendar_specific_datetime(date, calendar, False, has_year_zero=has_year_zero)
td = date - basedate
if td % unit_timedelta == timedelta(0):
# Explicitly cast result to np.int64 for Windows compatibility
quotient = np.int64(td // unit_timedelta)
times.append(quotient)
else:
if longdouble:
# Division of timedelta's is in float64 precision,
# i.e. losing microsecond precision.
# Conversion to float128 helps but can still lead to imprecision
# of +-1 microsecond in division:
# quotient = (np.longdouble(td.total_seconds()) /
# np.longdouble(unit_timedelta.total_seconds()))
# -> Convert to (64-bit) integers of microseconds
mtd = (td.days * 86400000000 +
td.seconds * 1000000 +
td.microseconds)
munit = (unit_timedelta.days * 86400000000 +
unit_timedelta.seconds * 1000000 +
unit_timedelta.microseconds)
quotient = np.longdouble(mtd) / np.longdouble(munit)
else:
quotient = td / unit_timedelta
times.append(quotient)
if ismasked: # convert to masked array if input was masked array
times = np.array(times, dtype=float) # None -> nan
times = np.ma.masked_invalid(times)
if isscalar:
return times[0]
else:
return np.reshape(times, shape)
if isscalar:
return times[0]
else:
return np.reshape(np.array(times), shape)
@cython.embedsignature(True)
def num2pydate(times,units,calendar='standard'):
"""
Always returns python datetime.datetime
objects and raise an error if this is not possible.
Same as
num2date(times,units,calendar,only_use_cftime_datetimes=False,only_use_python_datetimes=True)
"""
return num2date(times,units,calendar,only_use_cftime_datetimes=False,only_use_python_datetimes=True)
UNIT_CONVERSION_FACTORS = {
"microseconds": 1,
"microsecond": 1,
"microsec": 1,
"microsecs": 1,
"milliseconds": 1000,
"millisecond": 1000,
"millisec": 1000,
"millisecs": 1000,
"msec": 1000,
"msecs": 1000,
"ms": 1000,
"seconds": 1000000,
"second": 1000000,
"sec": 1000000,
"secs": 1000000,
"s": 1000000,
"minutes": 60 * 1000000,
"minute": 60 * 1000000,
"min": 60 * 1000000,
"mins": 60 * 1000000,
"hours": 3600 * 1000000,
"hour": 3600 * 1000000,
"hr": 3600 * 1000000,
"hrs": 3600 * 1000000,
"h": 3600 * 1000000,
"day": 86400 * 1000000,
"days": 86400 * 1000000,
"d": 86400 * 1000000,
"month": 30 * 86400 * 1000000, # Only allowed for 360_day calendar
"months": 30 * 86400 * 1000000,
"common_year": 365 * 86400 * 1000000, # Only allowed for 365_day and no_leap calendars
"common_years": 365 * 86400 * 1000000 # Only allowed for 365_day and no_leap calendars
}
DATE_TYPES = {
"proleptic_gregorian": DatetimeProlepticGregorian,
"standard": DatetimeGregorian,
"noleap": DatetimeNoLeap,
"365_day": DatetimeNoLeap,
"all_leap": DatetimeAllLeap,
"366_day": DatetimeAllLeap,
"julian": DatetimeJulian,
"360_day": Datetime360Day,
"gregorian": DatetimeGregorian
}
def to_calendar_specific_datetime(dt, calendar, use_python_datetime,has_year_zero=None):
if use_python_datetime:
return real_datetime(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond)
else:
date_type = DATE_TYPES[calendar]
return date_type(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
calendar=calendar,has_year_zero=has_year_zero)
_MAX_INT64 = np.iinfo("int64").max
_MIN_INT64 = np.iinfo("int64").min
def cast_to_int(num, units=None):
if num.dtype.kind in "iu":
return num
else:
#if np.any(num < _MIN_INT64) or np.any(num > _MAX_INT64):
# use this instead to avoid test failures on windows with numpy 1.23.0 (issue #279)
if np.any(np.less(num,_MIN_INT64,casting='same_kind')) or np.any(np.greater(num,_MAX_INT64,casting='same_kind')):
raise OverflowError('time values outside range of 64 bit signed integers')
if isinstance(num, np.ma.core.MaskedArray):
int_num = np.ma.masked_array(np.rint(num), dtype=np.int64)
# use ceil instead of rint if 1 microsec less than a second
# or floor if 1 microsec greater than a second (issue #187)
if units not in microsec_units and units not in millisec_units:
int_num = np.ma.where(int_num%1000000 == 1, \
np.ma.masked_array(np.floor(num),dtype=np.int64), int_num)
int_num = np.ma.where(int_num%1000000 == 999999, \
np.ma.masked_array(np.ceil(num),dtype=np.int64), int_num)
else:
int_num = np.array(np.rint(num), dtype=np.int64)
if units not in microsec_units and units not in millisec_units:
int_num = np.where(int_num%1000000 == 1, \
np.array(np.floor(num),dtype=np.int64), int_num)
int_num = np.where(int_num%1000000 == 999999, \
np.array(np.ceil(num),dtype=np.int64), int_num)
return int_num
def upcast_times(num):
"""Cast times array to larger float or integer dtype before scaling
to units of microseconds.
"""
if num.dtype.kind == "f":
return num.astype(np.longdouble)
else:
return num.astype(np.int64)
def scale_times(num, factor):
"""Scale times by a factor, raise an error if values will not fit in np.int64"""
if num.dtype.kind == "f":
return factor * num
else:
if num.size == 0: # empty array (issue #287)
return num
# Python integers have arbitrary precision, so convert min and max
# returned by NumPy functions through item, prior to multiplying by
# factor.
minimum = np.min(num).item() * factor
maximum = np.max(num).item() * factor
if minimum < _MIN_INT64 or maximum > _MAX_INT64:
# allowable time range = 292,471 years
raise OverflowError('time values outside range of 64 bit signed integers')
else:
return num * factor
def decode_date_from_scalar(time_in_microseconds, basedate):
"""Decode a date from a scalar input."""
delta = time_in_microseconds.astype("timedelta64[us]").astype(timedelta)
try:
return basedate + delta
except OverflowError:
raise ValueError("OverflowError in datetime, possibly because year < datetime.MINYEAR")
def decode_dates_from_array(times_in_microseconds, basedate):
"""Decode values encoded by an integer array in units of microseconds to dates.
This is an optimized algorithm that operates by flattening and sorting the input
array of integers, decoding the first date using the original base date, and then
incrementally adding timedeltas to decode the rest of the dates in the array. This
is an optimal approach, because it minimizes the length of the timedeltas used in
each addition operation required to decode the times (timedelta addition is the rate
limiting step in the process). The original order of the elements and shape of the
array are restored at the end. The sorting and unsorting steps add only a small
overhead. See discussion and timing results in GitHub issue 269.
"""
original_shape = times_in_microseconds.shape
times_in_microseconds = times_in_microseconds.ravel()
sort_indices = np.argsort(times_in_microseconds)
unsort_indices = np.argsort(sort_indices)
times_in_microseconds = times_in_microseconds[sort_indices]
# We first cast to the np.timedelta64[us] dtype out of convenience, but ultimately
# cast to datetime.timedelta objects for operations with cftime objects (we cannot
# cast from integers to datetime.timedelta objects directly).
deltas = times_in_microseconds.astype("timedelta64[us]")
differential_deltas = np.diff(deltas).astype(timedelta)
dates = np.empty(times_in_microseconds.shape, dtype="O")
try:
dates[0] = basedate + deltas[0].astype(timedelta)
for i in range(len(differential_deltas)):
dates[i + 1] = dates[i] + differential_deltas[i]
except OverflowError:
raise ValueError("OverflowError in datetime, possibly because year < datetime.MINYEAR")
return dates[unsort_indices].reshape(original_shape)
@cython.embedsignature(True)
def num2date(
times,
units,
calendar='standard',
only_use_cftime_datetimes=True,
only_use_python_datetimes=False,
has_year_zero=None
):
"""
Return datetime objects given numeric time values. The units
of the numeric time values are described by the **units** argument
and the **calendar** keyword. The returned datetime objects represent
UTC with no time-zone offset, even if the specified
**units** contain a time-zone offset.
**times**: numeric time values.
**units**: a string of the form **<time units> since <reference time>**
describing the time units. **<time units>** can be days, hours, minutes,
seconds, milliseconds or microseconds. **<reference time>** is the time
origin. **months since** is allowed *only* for the **360_day** calendar
and **common_years since** is allowed *only* for the **365_day** calendar.
**calendar**: describes the calendar used in the time calculations.
All the values currently defined in the
`CF metadata convention <https://cfconventions.org/cf-conventions/cf-conventions#calendar>`__ are supported.
Valid calendars **'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'**.
Default is **'standard'**, which is a mixed Julian/Gregorian calendar.
**only_use_cftime_datetimes**: if False, python datetime.datetime
objects are returned from num2date where possible; if True dates which
subclass cftime.datetime are returned for all calendars. Default **True**.
**only_use_python_datetimes**: always return python datetime.datetime
objects and raise an error if this is not possible. Ignored unless
**only_use_cftime_datetimes=False**. Default **False**.
**has_year_zero**: if set to True, astronomical year numbering
is used and the year zero exists. If set to False for real-world
calendars, then historical year numbering is used and the year 1 is
preceded by year -1 and no year zero exists.
The defaults are set to conform with
CF version 1.9 conventions (False for 'julian', 'gregorian'/'standard', True
for 'proleptic_gregorian' (ISO 8601) and True for the idealized
calendars 'noleap'/'365_day', '360_day', 366_day'/'all_leap')
The defaults can only be over-ridden for the real-world calendars,
for the the idealized calendars the year zero
always exists and the has_year_zero kwarg is ignored.
This kwarg is not needed to define calendar systems allowed by CF
(the calendar-specific defaults do this).
returns a datetime instance, or an array of datetime instances with
microsecond accuracy, if possible.
***Note***: If only_use_cftime_datetimes=False and
use_only_python_datetimes=False, the datetime instances
returned are 'real' python datetime
objects if **calendar='proleptic_gregorian'**, or
**calendar='standard'** or **'gregorian'**
and the date is after the breakpoint between the Julian and
Gregorian calendars (1582-10-15). Otherwise, they are ctime.datetime
objects which support some but not all the methods of native python
datetime objects. The datetime instances
do not contain a time-zone offset, even if the specified **units**
contains one.
"""
calendar = calendar.lower()
# set calendar-specific defaults for has_year_zero
if has_year_zero is None:
has_year_zero = _year_zero_defaults(calendar)
basedate = _dateparse(units,calendar=calendar,has_year_zero=has_year_zero)
can_use_python_datetime=_can_use_python_datetime(basedate,calendar)
if not only_use_cftime_datetimes and only_use_python_datetimes:
if not can_use_python_datetime:
msg='illegal calendar or reference date for python datetime'
raise ValueError(msg)
unit, ignore = _datesplit(units)
# real-world calendars limited to positive reference years.
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian'] and not has_year_zero:
if basedate.year == 0:
msg='zero not allowed as a reference year unless has_year_zero=True'
raise ValueError(msg)
use_python_datetime = False
if only_use_python_datetimes and not only_use_cftime_datetimes:
# only_use_cftime_datetimes takes precedence
use_python_datetime = True
if not only_use_python_datetimes and not only_use_cftime_datetimes and can_use_python_datetime:
# if only_use_cftimes_datetimes and only_use_python_datetimes are False
# return python datetime if possible.
use_python_datetime = True
basedate = to_calendar_specific_datetime(basedate, calendar, use_python_datetime, has_year_zero=has_year_zero)
if unit not in UNIT_CONVERSION_FACTORS:
raise ValueError("Unsupported time units provided, {!r}.".format(unit))
if unit in ["months", "month"] and calendar != "360_day":
raise ValueError("Units of months only valid for 360_day calendar.")
factor = UNIT_CONVERSION_FACTORS[unit]
times = np.asanyarray(times) # Allow list as input
times = upcast_times(times)
scaled_times = scale_times(times, factor)
scaled_times = cast_to_int(scaled_times,units=unit)
if scaled_times.ndim == 0 or scaled_times.size == 0:
return decode_date_from_scalar(scaled_times, basedate)
else:
if isinstance(scaled_times, np.ma.MaskedArray):
# The algorithm requires data be present for all values. To handle this, we fill
# masked values with 0 temporarily and then restore the mask at the end.
original_mask = np.ma.getmask(scaled_times)
scaled_times = scaled_times.filled(0)
dates = decode_dates_from_array(scaled_times, basedate)
return np.ma.MaskedArray(dates, mask=original_mask)
else:
return decode_dates_from_array(scaled_times, basedate)
@cython.embedsignature(True)
def date2index(dates, nctime, calendar=None, select='exact', has_year_zero=None):
"""
Return indices of a netCDF time variable corresponding to the given dates.
**dates**: A datetime object or a sequence of datetime objects.
The datetime objects should not include a time-zone offset.
**nctime**: A netCDF time variable object. The nctime object must have a
**units** attribute.
**calendar**: describes the calendar to be used in the time calculations.
All the values currently defined in the
`CF metadata convention <https://cfconventions.org/cf-conventions/cf-conventions#calendar>`__ are supported.
Valid calendars **'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'**.
Default is `None` which means the calendar associated with the first
input datetime instance will be used.
**select**: **'exact', 'before', 'after', 'nearest'**
The index selection method. **exact** will return the indices perfectly
matching the dates given. **before** and **after** will return the indices
corresponding to the dates just before or just after the given dates if
an exact match cannot be found. **nearest** will return the indices that
correspond to the closest dates.
**has_year_zero**: if set to True, astronomical year numbering
is used and the year zero exists. If set to False for real-world
calendars, then historical year numbering is used and the year 1 is
preceded by year -1 and no year zero exists.
The defaults are set to conform with
CF version 1.9 conventions (False for 'julian', 'gregorian'/'standard', True
for 'proleptic_gregorian' (ISO 8601) and True for the idealized
calendars 'noleap'/'365_day', '360_day', 366_day'/'all_leap')
The defaults can only be over-ridden for the real-world calendars,
for the the idealized calendars the year zero
always exists and the has_year_zero kwarg is ignored.
This kwarg is not needed to define calendar systems allowed by CF
(the calendar-specific defaults do this).
returns an index (indices) of the netCDF time variable corresponding
to the given datetime object(s).
"""
try:
nctime.units
except AttributeError:
raise AttributeError("netcdf time variable is missing a 'units' attribute")
dates_test = np.asanyarray(dates) # convert to numpy array
# if has_year_zero is None and calendar is None, use first input cftime.datetime instance
# to determine if year zero is to be included.
# If calendar is specified, use calendar specific defaults
if has_year_zero is None:
if calendar is None:
d0 = dates_test.item(0)
if isinstance(d0,datetime_python):
has_year_zero = False
else:
try:
has_year_zero = d0.has_year_zero
except AttributeError:
raise ValueError('has_year_zero not specified',type(d0))
else:
has_year_zero = _year_zero_defaults(calendar)
# if calendar is None or '', use calendar of first input cftime.datetime instances.
# if inputs are 'real' python datetime instances, use propleptic gregorian.
if not calendar:
d0 = dates_test.item(0)
if isinstance(d0,datetime_python):
calendar = 'proleptic_gregorian'
else:
try:
calendar = d0.calendar
except AttributeError:
raise ValueError('no calendar specified',type(d0))
calendar = calendar.lower()
basedate = _dateparse(nctime.units,calendar=calendar,has_year_zero=has_year_zero)
# real-world calendars limited to positive reference years.
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian'] and not has_year_zero:
if basedate.year == 0:
msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
raise ValueError(msg)
if _can_use_python_datetime(basedate,calendar):
# use python datetime
times = date2num(dates,nctime.units,calendar=calendar,has_year_zero=has_year_zero)
return time2index(times, nctime, calendar, select)
else: # use cftime module for other cases
return _date2index(dates, nctime, calendar, select, has_year_zero=has_year_zero)
cdef _parse_timezone(tzstring):
"""Parses ISO 8601 time zone specs into tzinfo offsets
Adapted from pyiso8601 (https://code.google.com/p/pyiso8601/)
"""
if tzstring == "Z":
return 0
# This isn't strictly correct, but it's common to encounter dates without
# time zones so I'll assume the default (which defaults to UTC).
if tzstring is None:
return 0
m = TIMEZONE_REGEX.match(tzstring)
prefix, hours, minutes1, minutes2 = m.groups()
hours = int(hours)
# Note: Minutes don't have to be specified in tzstring, so if the group is not found it means minutes is 0.
# Also, due to the timezone regex definition, there are two mutually exclusive groups that might hold the minutes value, so check both.
minutes = int(minutes1) if minutes1 is not None else int(minutes2) if minutes2 is not None else 0
if prefix == "-":
hours = -hours
minutes = -minutes
return minutes + hours * 60.
cpdef _parse_date(datestring):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string, assuming UTC
by default.
Note that a seconds element with a fractional component
(e.g. 12.5) is converted into integer seconds and integer
microseconds.
Adapted from pyiso8601 (https://code.google.com/p/pyiso8601/)
"""
if not isinstance(datestring, str) and not isinstance(datestring, unicode):
raise ValueError("Expecting a string %r" % datestring)
m = ISO8601_REGEX.match(datestring.strip())
if not m:
raise ValueError("Unable to parse date string %r" % datestring)
groups = m.groupdict()
tzoffset_mins = _parse_timezone(groups["timezone"])
if groups["hour"] is None:
groups["hour"] = 0
if groups["minute"] is None:
groups["minute"] = 0
if groups["second"] is None:
groups["second"] = 0
if groups["fraction"] is None:
groups["fraction"] = 0
else:
groups["fraction"] = int(float("0.%s" % groups["fraction"]) * 1e6)
iyear = int(groups["year"])
return iyear, int(groups["month"]), int(groups["day"]),\
int(groups["hour"]), int(groups["minute"]), int(groups["second"]),\
int(groups["fraction"]),\
tzoffset_mins
cdef _check_index(indices, times, nctime, select):
"""Return True if the time indices given correspond to the given times,
False otherwise.
Parameters:
indices : sequence of integers
Positive integers indexing the time variable.
times : sequence of times.
Reference times.
nctime : netCDF Variable object
NetCDF time object.
select : string
Index selection method.
"""
N = nctime.shape[0]
if (indices < 0).any():
return False
if (indices >= N).any():
return False
try:
t = nctime[indices]
nctime = nctime
# WORKAROUND TO CHANGES IN SLICING BEHAVIOUR in 1.1.2
# this may be unacceptably slow...
# if indices are unsorted, or there are duplicate
# values in indices, read entire time variable into numpy
# array so numpy slicing rules can be used.
except IndexError:
nctime = nctime[:]
t = nctime[indices]
# if fancy indexing not available, fall back on this.
# t=[]
# for ind in indices:
# t.append(nctime[ind])
if select == 'exact':
return np.all(t == times)
elif select == 'before':
ta = nctime[np.clip(indices + 1, 0, N - 1)]
return np.all(t <= times) and np.all(ta > times)
elif select == 'after':
tb = nctime[np.clip(indices - 1, 0, N - 1)]
return np.all(t >= times) and np.all(tb < times)
elif select == 'nearest':
ta = nctime[np.clip(indices + 1, 0, N - 1)]
tb = nctime[np.clip(indices - 1, 0, N - 1)]
delta_after = ta - t
delta_before = t - tb
delta_check = np.abs(times - t)
return np.all(delta_check <= delta_after) and np.all(delta_check <= delta_before)
def _date2index(dates, nctime, calendar=None, select='exact', has_year_zero=None):
"""
Return indices of a netCDF time variable corresponding to the given dates.
**dates**: A datetime object or a sequence of datetime objects.
The datetime objects should not include a time-zone offset.
**nctime**: A netCDF time variable object. The nctime object must have a
`units` attribute. The entries are assumed to be stored in increasing
order.
**calendar**: Describes the calendar used in the time calculation.
Valid calendars 'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'.
Default is 'standard', which is a mixed Julian/Gregorian calendar
If `calendar` is None, its value is given by `nctime.calendar` or
`standard` if no such attribute exists.
**select**: 'exact', 'before', 'after', 'nearest'
The index selection method. `exact` will return the indices perfectly
matching the dates given. `before` and `after` will return the indices
corresponding to the dates just before or just after the given dates if
an exact match cannot be found. `nearest` will return the indices that
correspond to the closest dates.
**has_year_zero**: if set to True, astronomical year numbering
is used and the year zero exists. If set to False for real-world
calendars, then historical year numbering is used and the year 1 is
preceded by year -1 and no year zero exists.
The defaults are set to conform with
CF version 1.9 conventions (False for 'julian', 'gregorian'/'standard', True
for 'proleptic_gregorian' (ISO 8601) and True for the idealized
calendars 'noleap'/'365_day', '360_day', 366_day'/'all_leap')
The defaults can only be over-ridden for the real-world calendars,
for the the idealized calendars the year zero
always exists and the has_year_zero kwarg is ignored.
This kwarg is not needed to define calendar systems allowed by CF
(the calendar-specific defaults do this).
"""
try:
nctime.units
except AttributeError:
raise AttributeError("netcdf time variable is missing a 'units' attribute")
times = date2num(dates,nctime.units,calendar=calendar, has_year_zero=has_year_zero)
return time2index(times, nctime, calendar=calendar, select=select)
@cython.embedsignature(True)
def time2index(times, nctime, calendar=None, select='exact'):
"""
Return indices of a netCDF time variable corresponding to the given times.
**times**: A numeric time or a sequence of numeric times.
**nctime**: A netCDF time variable object. The nctime object must have a
`units` attribute. The entries are assumed to be stored in increasing
order.
**calendar**: Describes the calendar used in the time calculation.
Valid calendars 'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'.
Default is `standard`, which is a mixed Julian/Gregorian calendar
If `calendar` is None, its value is given by `nctime.calendar` or
`standard` if no such attribute exists.
**select**: **'exact', 'before', 'after', 'nearest'**
The index selection method. `exact` will return the indices perfectly
matching the times given. `before` and `after` will return the indices
corresponding to the times just before or just after the given times if
an exact match cannot be found. `nearest` will return the indices that
correspond to the closest times.
"""
try:
nctime.units
except AttributeError:
raise AttributeError("netcdf time variable is missing a 'units' attribute")
# Setting the calendar.
if calendar == None:
calendar = getattr(nctime, 'calendar', 'standard')
if select != 'exact':
# if select works, then 'nearest' == 'exact', 'before' == 'exact'-1 and
# 'after' == 'exact'+1
try:
index = time2index(times, nctime, calendar=calendar, select='exact')
if select == 'nearest':
return index
elif select == 'before':
return index-1
else:
return index+1
except ValueError:
pass
num = np.atleast_1d(times)
N = len(nctime)
# Trying to infer the correct index from the starting time and the stride.
# This assumes that the times are increasing uniformly.
if len(nctime) >= 2:
t0, t1 = nctime[:2]
dt = t1 - t0
else:
t0 = nctime[0]
dt = 1.
if select in ['exact', 'before']:
index = np.array((num - t0) / dt, int)
elif select == 'after':
index = np.array(np.ceil((num - t0) / dt), int)
else:
index = np.array(np.around((num - t0) / dt), int)
# Checking that the index really corresponds to the given time.
# If the times do not correspond, then it means that the times
# are not increasing uniformly and we try the bisection method.
if not _check_index(index, times, nctime, select):
# Use the bisection method. Assumes nctime is ordered.
import bisect
index = np.array([bisect.bisect_right(nctime, n) for n in num], int)
before = index == 0
index = np.array([bisect.bisect_left(nctime, n) for n in num], int)
after = index == N
if select in ['before', 'exact'] and np.any(before):
raise ValueError(
'Some of the times given are before the first time in **nctime**.')
if select in ['after', 'exact'] and np.any(after):
raise ValueError(
'Some of the times given are after the last time in **nctime**.')
# Find the times for which the match is not perfect.
# Use list comprehension instead of the simpler **nctime[index]** since
# not all time objects support numpy integer indexing (eg dap).
index[after] = N - 1
ncnum = np.squeeze([nctime[i] for i in index])
mismatch = np.nonzero(ncnum != num)[0]
if select == 'exact':
if len(mismatch) > 0:
raise ValueError(
'Some of the times specified were not found in the **nctime** variable.')
elif select == 'before':
index[after] = N
index[mismatch] -= 1
elif select == 'after':
pass
elif select == 'nearest':
nearest_to_left = num[mismatch] < np.array(
[float(nctime[i - 1]) + float(nctime[i]) for i in index[mismatch]]) / 2.
index[mismatch] = index[mismatch] - 1 * nearest_to_left