-
Notifications
You must be signed in to change notification settings - Fork 40
/
_cftime.py
2189 lines (1857 loc) · 82.3 KB
/
_cftime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Performs conversions of netCDF time coordinate data to/from datetime objects.
"""
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
#from _cftime_utils import add_timedelta, add_timedelta_360_day, _IntJulianDayFromDate, _is_leap, _IntJulianDayToDate
try:
from itertools import izip as zip
except ImportError: # python 3.x
pass
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
_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 http://cfconventions.org/cf-conventions/cf-conventions.html#calendar
# for definitions.
_calendars = ['standard', 'gregorian', 'proleptic_gregorian',
'noleap', 'julian', 'all_leap', '365_day', '366_day', '360_day']
# Following are number of Days Per Month
_dpm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
_dpm_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
_dpm_360 = [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
# Same as above, but SUM of previous months (no leap years).
_spm_365day = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
_spm_366day = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
# Slightly more performant lookups than a 2D table
# The first 12 entries correspond to month lengths for non-leap years.
# The remaining 12 entries give month lengths for leap years
days_per_month_array = [
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
__version__ = '1.2.1'
# Adapted from http://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]{1,4})(-(?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 redifinition 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}))?")
# Taken from pandas ccalendar.pyx
def get_days_in_month(isleap, month):
"""
Return the number of days in the given month of the given year.
Parameters
----------
leap : int [0,1]
month : int
Returns
-------
days_in_month : int
Notes
-----
Assumes that the arguments are valid. Passing a month not between 1 and 12
risks a segfault.
"""
return days_per_month_array[12 * isleap + month - 1]
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):
return get_days_in_month(_is_leap(self.year,'proleptic_gregorian'), self.month)
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):
"""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.
(units, isostring) = _datesplit(timestr)
if not ((units in month_units and calendar=='360_day') or units in _units):
if units in month_units and calendar != '360_day':
raise ValueError("'months since' units only allowed for '360_day' calendar")
else:
raise ValueError(
"units must be one of 'seconds', 'minutes', 'hours' or 'days' (or singular version of these), got '%s'" % units)
# parse the date string.
year, month, day, hour, minute, second, microsecond, utc_offset =\
_parse_date( isostring.strip() )
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
if year == 0:
msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
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 = None
if year >= MINYEAR and year <= MAXYEAR:
try:
basedate = real_datetime(year, month, day, hour, minute, second,
microsecond)
# subtract utc_offset from basedate time instance (which is timezone naive)
basedate -= timedelta(days=utc_offset/1440.)
except ValueError:
pass
if not basedate:
if not utc_offset:
basedate = datetime(year, month, day, hour, minute, second,
microsecond, calendar=calendar)
else:
raise ValueError('cannot use utc_offset for this reference date/calendar')
return basedate
def _can_use_python_datetime(date,calendar):
gregorian = datetime(1582,10,15,calendar=calendar)
return ((calendar == 'proleptic_gregorian' and date.year >= MINYEAR and date.year <= MAXYEAR) or \
(calendar in ['gregorian','standard'] and date > gregorian and date.year <= MAXYEAR))
def date2num(dates,units,calendar='standard'):
"""
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.
**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.
**calendar**: describes the calendar used in the time calculations.
All the values currently defined in the
[CF metadata convention](http://cfconventions.org)
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.
returns a numeric time value, or an array of numeric time values
with approximately 1 microsecond accuracy.
"""
calendar = calendar.lower()
basedate = _dateparse(units,calendar=calendar)
(unit, isostring) = _datesplit(units)
# real-world calendars limited to positive reference years.
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
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.")
factor = UNIT_CONVERSION_FACTORS[unit]
can_use_python_basedatetime = _can_use_python_datetime(basedate,calendar)
isscalar = False
try:
dates[0]
except:
isscalar = True
ismasked = False
if np.ma.isMA(dates) and np.ma.is_masked(dates):
mask = dates.mask
ismasked = True
dates = np.asanyarray(dates)
shape = dates.shape
# are all dates python datetime instances?
all_python_datetimes = True
for date in dates.flat:
if not isinstance(date,datetime_python):
all_python_datetimes = False
break
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
if not isinstance(basedate, DATE_TYPES[calendar]):
basedate = to_calendar_specific_datetime(basedate, calendar, False)
times = []; n = 0
for date in dates.flat:
# 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
if not isinstance(date, DATE_TYPES[calendar]):
date = to_calendar_specific_datetime(date, calendar, False)
if ismasked and mask.flat[n]:
times.append(None)
else:
td = date - basedate
if factor == 1.0:
# units are microseconds, use integer division
times.append(td // timedelta(microseconds=1) )
else:
#times.append( (td / timedelta(microseconds=1)) / factor )
# this appears to be faster.
times.append( (td.total_seconds()*1.e6) / factor )
n += 1
if ismasked: # convert to masked array if input was masked array
times = np.array(times)
times = np.ma.masked_where(times==None,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)
def num2pydate(times,units,calendar='standard'):
"""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
}
def to_calendar_specific_datetime(datetime, calendar, use_python_datetime):
if use_python_datetime:
date_type = real_datetime
else:
date_type = DATE_TYPES[calendar]
return date_type(
datetime.year,
datetime.month,
datetime.day,
datetime.hour,
datetime.minute,
datetime.second,
datetime.microsecond
)
_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):
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:
# 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 num2date(
times,
units,
calendar='standard',
only_use_cftime_datetimes=True,
only_use_python_datetimes=False
):
"""
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.
**calendar**: describes the calendar used in the time calculations.
All the values currently defined in the
[CF metadata convention](http://cfconventions.org)
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**.
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()
basedate = _dateparse(units,calendar=calendar)
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']:
if basedate.year == 0:
msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
raise ValueError(msg)
use_python_datetime = False
if only_use_python_datetimes and not only_use_cftime_datetimes:
# only_use_cftime_datetimes takes precendence
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)
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)
# Through np.timedelta64, convert integers scaled to have units of
# microseconds to datetime.timedelta objects, the timedelta type compatible
# with all cftime.datetime objects.
deltas = scaled_times.astype("timedelta64[us]").astype(timedelta)
try:
return basedate + deltas
except OverflowError:
raise ValueError("OverflowError in datetime, possibly because year < datetime.MINYEAR")
def date2index(dates, nctime, calendar=None, select='exact'):
"""
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 used in the time calculations.
All the values currently defined in the
[CF metadata convention](http://cfconventions.org)
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.
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")
if calendar == None:
calendar = getattr(nctime, 'calendar', 'standard')
calendar = calendar.lower()
basedate = _dateparse(nctime.units,calendar=calendar)
# real-world calendars limited to positive reference years.
if calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
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)
return time2index(times, nctime, calendar, select)
else: # use cftime module for other cases
return _date2index(dates, nctime, calendar, select)
def _parse_timezone(tzstring):
"""Parses ISO 8601 time zone specs into tzinfo offsets
Adapted from pyiso8601 (http://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.
def _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 (http://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
def _check_index(indices, times, nctime, calendar, 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.
calendar : string
Calendar of nctime.
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'):
"""
_date2index(dates, nctime, calendar=None, select='exact')
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
C{units} attribute. The entries are assumed to be stored in increasing
order.
**calendar**: Describes the calendar used in the time calculation.
Valid calendars C{'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'}.
Default is C{'standard'}, which is a mixed Julian/Gregorian calendar
If C{calendar} is None, its value is given by C{nctime.calendar} or
C{standard} if no such attribute exists.
**select**: C{'exact', 'before', 'after', 'nearest'}
The index selection method. C{exact} will return the indices perfectly
matching the dates given. C{before} and C{after} will return the indices
corresponding to the dates just before or just after the given dates if
an exact match cannot be found. C{nearest} will return the indices that
correspond to the closest dates.
"""
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')
times = date2num(dates,nctime.units,calendar=calendar)
return time2index(times, nctime, calendar=calendar, select=select)
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
C{units} attribute. The entries are assumed to be stored in increasing
order.
**calendar**: Describes the calendar used in the time calculation.
Valid calendars C{'standard', 'gregorian', 'proleptic_gregorian'
'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'}.
Default is C{'standard'}, which is a mixed Julian/Gregorian calendar
If C{calendar} is None, its value is given by C{nctime.calendar} or
C{standard} if no such attribute exists.
**select**: **'exact', 'before', 'after', 'nearest'**
The index selection method. C{exact} will return the indices perfectly
matching the times given. C{before} and C{after} will return the indices
corresponding to the times just before or just after the given times if
an exact match cannot be found. C{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')
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, calendar, 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
else:
raise ValueError(
"%s is not an option for the **select** argument." % select)
# Correct for indices equal to -1
index[before] = 0
# convert numpy scalars or single element arrays to python ints.
return _toscalar(index)
def _toscalar(a):
if a.shape in [(), (1,)]:
return a.item()
else:
return a
def to_tuple(dt):
"""Turn a datetime.datetime instance into a tuple of integers. Elements go
in the order of decreasing significance, making it easy to compare
datetime instances. Parts of the state that don't affect ordering
are omitted. Compare to datetime.timetuple()."""
return (dt.year, dt.month, dt.day, dt.hour, dt.minute,
dt.second, dt.microsecond)
class datetime(object):
"""
The base class implementing most methods of datetime classes that
mimic datetime.datetime but support calendars other than the proleptic
Gregorian calendar.
Calendar specific sub-classes support timedelta operations by overloading +/-.
Comparisons with other datetime_base sub-class instances using the same
calendar are supported.
Comparison with native python datetime instances is possible
for cftime.datetime_base sub-class instances using
'gregorian' and 'proleptic_gregorian' calendars.
If a 'calendar' keyword argument is supplied to the constructor, then
a calendar-aware instance is created. If not calendar is specified, the
instance will not be calendar-aware and some methods will not work.
Has isoformat, strftime, timetuple, replace, dayofwk, dayofyr, daysinmonth,
__repr__, __add__, __sub__, __str__ and comparison methods.
dayofwk, dayofyr, daysinmonth, __add__ and __sub__ only work for calendar-aware
instances.
The default format of the string produced by strftime is controlled by self.format
(default %Y-%m-%d %H:%M:%S).
"""
def __new__(cls, year, month, day, hour=0, minute=0,
second=0, microsecond=0, dayofwk=-1,
dayofyr = -1, calendar=None):
if not calendar:
# needed to avoid infinite recursion
# if calendar is not set, then datetime instance
# is not 'calendar aware', meaning dayofwk, dayofyr,
# daysinmonth, __add__ and __sub__ methods will not work.
return object.__new__(cls)
else:
# return calendar-aware subclass.
date_type = DATE_TYPES[calendar]
return date_type(year,month,day,hour,minute,second,microsecond)
def __init__(self, year, month, day, hour=0, minute=0,
second=0, microsecond=0, dayofwk=-1,
dayofyr = -1, calendar=None):
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.microsecond = microsecond
self.calendar = calendar
self._dayofwk = dayofwk
self._dayofyr = dayofyr
# Python's datetime.datetime uses the proleptic Gregorian
# calendar. This boolean is used to decide whether a
# cftime.datetime instance can be converted to
# datetime.datetime.
self.datetime_compatible = False
@property
def format(self):
return '%Y-%m-%d %H:%M:%S'
@property
def dayofwk(self):
if self._dayofwk < 0 and self.calendar:
jd = _IntJulianDayFromDate(self.year,self.month,self.day,self.calendar)
year,month,day,dayofwk,dayofyr = _IntJulianDayToDate(jd,self.calendar)
# cache results for dayofwk, dayofyr
self._dayofwk = dayofwk
self._dayofyr = dayofyr
return dayofwk
else:
return self._dayofwk
@property
def dayofyr(self):
if self._dayofyr < 0 and self.calendar:
jd = _IntJulianDayFromDate(self.year,self.month,self.day,self.calendar)
year,month,day,dayofwk,dayofyr = _IntJulianDayToDate(jd,self.calendar)
# cache results for dayofwk, dayofyr
self._dayofwk = dayofwk
self._dayofyr = dayofyr
return dayofyr
else:
return self._dayofyr
@property
def daysinmonth(self):
return get_days_in_month(_is_leap(self.year,self.calendar), self.month)
def strftime(self, format=None):
"""
Return a string representing the date, controlled by an explicit format
string. For a complete list of formatting directives, see section
'strftime() and strptime() Behavior' in the base Python documentation.
"""
if format is None:
format = self.format
return _strftime(self, format)
def replace(self, **kwargs):
"""Return datetime with new specified fields."""
args = {"year": self.year,
"month": self.month,
"day": self.day,
"hour": self.hour,
"minute": self.minute,
"second": self.second,
"microsecond": self.microsecond,
"calendar": self.calendar}
if 'dayofyr' in kwargs or 'dayofwk' in kwargs:
raise ValueError('Replacing the dayofyr or dayofwk of a datetime is '
'not supported.')
if 'calendar' in kwargs:
raise ValueError('Replacing the calendar of a datetime is '
'not supported.')
for name, value in kwargs.items():
args[name] = value
return self.__class__(**args)
def timetuple(self):
"""
Return a time.struct_time such as returned by time.localtime().
The DST flag is -1. d.timetuple() is equivalent to
time.struct_time((d.year, d.month, d.day, d.hour, d.minute,
d.second, d.weekday(), yday, dst)), where yday is the
day number within the current year starting with 1 for January 1st.
"""
return time.struct_time((self.year, self.month, self.day, self.hour,
self.minute, self.second, self.dayofwk, self.dayofyr, -1))
def _to_real_datetime(self):
return real_datetime(self.year, self.month, self.day,
self.hour, self.minute, self.second,
self.microsecond)
def __repr__(self):
return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
self.__class__.__name__,
self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
def __str__(self):
return self.isoformat(' ')
def isoformat(self,sep='T',timespec='auto'):
second = ":%02i" %self.second
if (timespec == 'auto' and self.microsecond) or timespec == 'microseconds':
second += ".%06i" % self.microsecond
if timespec == 'milliseconds':
millisecs = self.microsecond/1000
second += ".%03i" % millisecs
if timespec in ['auto', 'microseconds', 'milliseconds']:
return "%04i-%02i-%02i%s%02i:%02i%s" %\
(self.year, self.month, self.day, sep, self.hour, self.minute, second)
elif timespec == 'seconds':
return "%04i-%02i-%02i%s%02i:%02i:%02i" %\
(self.year, self.month, self.day, sep, self.hour, self.minute, self.second)
elif timespec == 'minutes':
return "%04i-%02i-%02i%s%02i:%02i" %\
(self.year, self.month, self.day, sep, self.hour, self.minute)
elif timespec == 'hours':
return "%04i-%02i-%02i%s%02i" %\
(self.year, self.month, self.day, sep, self.hour)
else:
raise ValueError('illegal timespec')
def __hash__(self):
try:
d = self._to_real_datetime()
except ValueError:
return hash(self.timetuple())
return hash(d)
def to_tuple(self):
return (self.year, self.month, self.day, self.hour, self.minute,
self.second, self.microsecond)
def __eq__(self, other):
return self._cmp(other,"__eq__")
def __lt__(self, other):
return self._cmp(other,"__lt__")