-
Notifications
You must be signed in to change notification settings - Fork 40
/
_cftime.pyx
2076 lines (1785 loc) · 80.2 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)
import cython
import numpy as np
import re
import sys
import time
from datetime import datetime as datetime_python
from datetime import timedelta, MINYEAR
import time # strftime
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']
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
cdef int[12] _dpm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
cdef int[12] _dpm_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
cdef int[12] _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).
cdef int[13] _spm_365day = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
cdef int[13] _spm_366day = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
# Reverse operator lookup for datetime.__richcmp__
_rop_lookup = {Py_LT: '__gt__', Py_LE: '__ge__', Py_EQ: '__eq__',
Py_GT: '__lt__', Py_GE: '__le__', Py_NE: '__ne__'}
__version__ = '1.0.3.4'
# 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}))?")
class real_datetime(datetime_python):
"""add dayofwk and dayofyr 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
nanosecond = 0 # workaround for pandas bug (cftime issue #77)
# start of the gregorian calendar
gregorian = real_datetime(1582,10,15)
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):
"""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)
# parse the date string.
year, month, day, hour, minute, second, utc_offset =\
_parse_date( isostring.strip() )
if year >= MINYEAR:
basedate = real_datetime(year, month, day, hour, minute, second)
# subtract utc_offset from basedate time instance (which is timezone naive)
basedate -= timedelta(days=utc_offset/1440.)
else:
if not utc_offset:
basedate = datetime(year, month, day, hour, minute, second)
else:
raise ValueError('cannot use utc_offset for reference years <= 0')
return basedate
def _round_half_up(x):
# 'round half up' so 0.5 rounded to 1 (instead of 0 as in numpy.round)
return np.ceil(np.floor(2.*x)/2.)
cdef _parse_date_and_units(timestr,calendar='standard'):
"""parse a string of the form time-units since yyyy-mm-dd hh:mm:ss
return a tuple (units,utc_offset, datetimeinstance)"""
(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, utc_offset = _parse_date(
isostring.strip())
return units, utc_offset, datetime(year, month, day, hour, minute, second)
def date2num(dates,units,calendar='standard'):
"""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 100 microsecond accuracy.
"""
calendar = calendar.lower()
basedate = _dateparse(units)
(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)
if (calendar == 'proleptic_gregorian' and basedate.year >= MINYEAR) or \
(calendar in ['gregorian','standard'] and basedate > gregorian):
# use python datetime module,
isscalar = False
try:
dates[0]
except:
isscalar = True
if isscalar:
dates = np.array([dates])
else:
dates = np.array(dates)
shape = dates.shape
ismasked = False
if np.ma.isMA(dates) and np.ma.is_masked(dates):
mask = dates.mask
ismasked = True
times = []
for date in dates.flat:
if ismasked and not date:
times.append(None)
else:
td = date - basedate
# total time in microseconds.
totaltime = td.microseconds + (td.seconds + td.days * 24 * 3600) * 1.e6
if unit in microsec_units:
times.append(totaltime)
elif unit in millisec_units:
times.append(totaltime/1.e3)
elif unit in sec_units:
times.append(totaltime/1.e6)
elif unit in min_units:
times.append(totaltime/1.e6/60)
elif unit in hr_units:
times.append(totaltime/1.e6/3600)
elif unit in day_units:
times.append(totaltime/1.e6/3600./24.)
else:
raise ValueError('unsupported time units')
if isscalar:
return times[0]
else:
return np.reshape(np.array(times), shape)
else: # use cftime module for other calendars
cdftime = utime(units,calendar=calendar)
return cdftime.date2num(dates)
def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
"""num2date(times,units,calendar='standard')
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 (default), datetime.datetime
objects are returned from num2date where possible; if True dates which
subclass cftime.datetime are returned for all calendars.
returns a datetime instance, or an array of datetime instances with
approximately 100 microsecond accuracy.
***Note***: 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 'phony' datetime
objects which support some but not all the methods of 'real' 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)
(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)
postimes = (np.asarray(times) > 0).all() # netcdf4-python issue #659
if only_use_cftime_datetimes:
cdftime = utime(units, calendar=calendar,
only_use_cftime_datetimes=only_use_cftime_datetimes)
return cdftime.num2date(times)
elif postimes and ((calendar == 'proleptic_gregorian' and basedate.year >= MINYEAR) or \
(calendar in ['gregorian','standard'] and basedate > gregorian)):
# use python datetime module,
isscalar = False
try:
times[0]
except:
isscalar = True
if isscalar:
times = np.array([times],dtype='d')
else:
times = np.array(times, dtype='d')
shape = times.shape
ismasked = False
if np.ma.isMA(times) and np.ma.is_masked(times):
mask = times.mask
ismasked = True
dates = []
for time in times.flat:
if ismasked and not time:
dates.append(None)
else:
# convert to total seconds
if unit in microsec_units:
tsecs = time/1.e6
elif unit in millisec_units:
tsecs = time/1.e3
elif unit in sec_units:
tsecs = time
elif unit in min_units:
tsecs = time*60.
elif unit in hr_units:
tsecs = time*3600.
elif unit in day_units:
tsecs = time*86400.
else:
raise ValueError('unsupported time units')
# compute time delta.
days = tsecs // 86400.
msecsd = tsecs*1.e6 - days*86400.*1.e6
secs = msecsd // 1.e6
msecs = np.round(msecsd - secs*1.e6)
td = timedelta(days=days,seconds=secs,microseconds=msecs)
# add time delta to base date.
date = basedate + td
dates.append(date)
if isscalar:
return dates[0]
else:
return np.reshape(np.array(dates), shape)
else: # use cftime for other calendars
cdftime = utime(units,calendar=calendar)
return cdftime.num2date(times)
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
`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)
# 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 (calendar == 'proleptic_gregorian' and basedate.year >= MINYEAR) or \
(calendar in ['gregorian','standard'] and basedate > gregorian):
# 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 JulianDayFromDate(date, calendar='standard'):
"""JulianDayFromDate(date, calendar='standard')
creates a Julian Day from a 'datetime-like' object. Returns the fractional
Julian Day (approximately 100 microsecond accuracy).
if calendar='standard' or 'gregorian' (default), Julian day follows Julian
Calendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.
if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
if calendar='julian', Julian Day follows julian calendar.
"""
# check if input was scalar and change return accordingly
isscalar = False
try:
date[0]
except:
isscalar = True
date = np.atleast_1d(np.array(date))
year = np.empty(len(date), dtype=np.int32)
month = year.copy()
day = year.copy()
hour = year.copy()
minute = year.copy()
second = year.copy()
microsecond = year.copy()
jd = np.empty(year.shape, np.longdouble)
cdef long double[:] jd_view = jd
cdef Py_ssize_t i_max = len(date)
cdef Py_ssize_t i
for i in range(i_max):
d = date[i]
year[i] = d.year
month[i] = d.month
day[i] = d.day
hour[i] = d.hour
minute[i] = d.minute
second[i] = d.second
microsecond[i] = d.microsecond
jd_view[i] = <double>_IntJulianDayFromDate(<int>year[i],<int>month[i],<int>day[i],calendar)
# at this point jd is an integer representing noon UTC on the given
# year,month,day.
# compute fractional day from hour,minute,second,microsecond
fracday = hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
jd = jd - 0.5 + fracday
if isscalar:
return jd[0]
else:
return jd
def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False,
return_tuple=False):
"""
returns a 'datetime-like' object given Julian Day. Julian Day is a
fractional day with approximately 100 microsecond accuracy.
if calendar='standard' or 'gregorian' (default), Julian day follows Julian
Calendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.
if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
if calendar='julian', Julian Day follows julian calendar.
If only_use_cftime_datetimes is set to True, then cftime.datetime
objects are returned for all calendars. Otherwise the datetime object is a
'real' datetime object if the date falls in the Gregorian calendar
(i.e. calendar='proleptic_gregorian', or calendar = 'standard'/'gregorian'
and the date is after 1582-10-15). In all other cases a 'phony' datetime
objects are used, which are actually instances of cftime.datetime.
"""
julian = np.atleast_1d(np.array(JD, dtype=np.longdouble))
def getdateinfo(julian):
# get the day (Z) and the fraction of the day (F)
# use 'round half up' rounding instead of numpy's even rounding
# so that 0.5 is rounded to 1.0, not 0 (cftime issue #49)
Z = np.atleast_1d(np.int32(_round_half_up(julian)))
F = (julian + 0.5 - Z).astype(np.longdouble)
cdef Py_ssize_t i_max = len(Z)
year = np.empty(i_max, dtype=np.int32)
month = np.empty(i_max, dtype=np.int32)
day = np.empty(i_max, dtype=np.int32)
dayofyr = np.zeros(i_max,dtype=np.int32)
dayofwk = np.zeros(i_max,dtype=np.int32)
cdef int ijd
cdef Py_ssize_t i
for i in range(i_max):
ijd = Z[i]
year[i],month[i],day[i],dayofwk[i],dayofyr[i] = _IntJulianDayToDate(ijd,calendar)
if calendar in ['standard', 'gregorian']:
ind_before = np.where(julian < 2299160.5)[0]
else:
ind_before = None
# compute hour, minute, second, microsecond, convert to int32
hour = np.clip((F * 24.).astype(np.int64), 0, 23)
F -= hour / 24.
minute = np.clip((F * 1440.).astype(np.int64), 0, 59)
second = np.clip((F - minute / 1440.) * 86400., 0, None)
microsecond = (second % 1)*1.e6
hour = hour.astype(np.int32)
minute = minute.astype(np.int32)
second = second.astype(np.int32)
microsecond = microsecond.astype(np.int32)
return year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before
year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before =\
getdateinfo(julian)
# round to nearest second if within ms_eps microseconds
# (to avoid ugly errors in datetime formatting - alternative
# to adding small offset all the time as was done previously)
# see netcdf4-python issue #433 and cftime issue #78
# this is done by rounding microsends up or down, then
# recomputing year,month,day etc
# ms_eps is proportional to julian day,
# about 47 microseconds in 2000 for Julian base date in -4713
ms_eps = np.atleast_1d(np.array(np.finfo(np.float64).eps,np.longdouble))
ms_eps = 86400000000.*np.maximum(ms_eps*julian, ms_eps)
microsecond = np.where(microsecond < ms_eps, 0, microsecond)
indxms = microsecond > 1000000-ms_eps
if indxms.any():
julian[indxms] = julian[indxms] + 2*ms_eps[indxms]/86400000000.
year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before =\
getdateinfo(julian)
microsecond[indxms] = 0
# check if input was scalar and change return accordingly
isscalar = False
try:
JD[0]
except:
isscalar = True
is_real_dateime = False
if calendar == 'proleptic_gregorian':
# datetime.datetime does not support years < 1
#if year < 0:
if only_use_cftime_datetimes:
datetime_type = DatetimeProlepticGregorian
else:
if (year < 0).any(): # netcdftime issue #28
datetime_type = DatetimeProlepticGregorian
else:
is_real_datetime = True
datetime_type = real_datetime
elif calendar in ('standard', 'gregorian'):
# return a 'real' datetime instance if calendar is proleptic
# Gregorian or Gregorian and all dates are after the
# Julian/Gregorian transition
if len(ind_before) == 0 and not only_use_cftime_datetimes:
is_real_datetime = True
datetime_type = real_datetime
else:
is_real_datetime = False
datetime_type = DatetimeGregorian
elif calendar == "julian":
datetime_type = DatetimeJulian
elif calendar in ["noleap","365_day"]:
datetime_type = DatetimeNoLeap
elif calendar in ["all_leap","366_day"]:
datetime_type = DatetimeAllLeap
elif calendar == "360_day":
datetime_type = Datetime360Day
else:
raise ValueError("unsupported calendar: {0}".format(calendar))
if not isscalar:
if return_tuple:
return np.array([args for args in
zip(year, month, day, hour, minute, second,
microsecond,dayofwk,dayofyr)])
else:
if is_real_datetime:
return np.array([datetime_type(*args)
for args in
zip(year, month, day, hour, minute, second,
microsecond)])
else:
return np.array([datetime_type(*args)
for args in
zip(year, month, day, hour, minute, second,
microsecond,dayofwk,dayofyr)])
else:
if return_tuple:
return (year[0], month[0], day[0], hour[0],
minute[0], second[0], microsecond[0],
dayofwk[0], dayofyr[0])
else:
if is_real_datetime:
return datetime_type(year[0], month[0], day[0], hour[0],
minute[0], second[0], microsecond[0])
else:
return datetime_type(year[0], month[0], day[0], hour[0],
minute[0], second[0], microsecond[0],
dayofwk[0], dayofyr[0])
class utime:
"""
Performs conversions of netCDF time coordinate
data to/from datetime objects.
To initialize: C{t = utime(unit_string,calendar='standard')}
where
B{C{unit_string}} is a string of the form
C{'time-units since <time-origin>'} defining the time units.
Valid time-units are days, hours, minutes and seconds (the singular forms
are also accepted). An example unit_string would be C{'hours
since 0001-01-01 00:00:00'}. months is allowed as a time unit
*only* for the 360_day calendar.
The B{C{calendar}} keyword describes the calendar used in the time calculations.
All the values currently defined in the U{CF metadata convention
<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
are accepted. The default is C{'standard'}, which corresponds to the mixed
Gregorian/Julian calendar used by the C{udunits library}. Valid calendars
are:
C{'gregorian'} or C{'standard'} (default):
Mixed Gregorian/Julian calendar as defined by udunits.
C{'proleptic_gregorian'}:
A Gregorian calendar extended to dates before 1582-10-15. That is, a year
is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
it is divisible by 400.
C{'noleap'} or C{'365_day'}:
Gregorian calendar without leap years, i.e., all years are 365 days long.
all_leap or 366_day Gregorian calendar with every year being a leap year,
i.e., all years are 366 days long.
C{'360_day'}:
All years are 360 days divided into 30 day months.
C{'julian'}:
Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
leap year if it is divisible by 4.
The C{L{num2date}} and C{L{date2num}} class methods can used to convert datetime
instances to/from the specified time units using the specified calendar.
The datetime instances returned by C{num2date} are 'real' python datetime
objects if the date falls in the Gregorian calendar (i.e.
C{calendar='proleptic_gregorian', 'standard'} or C{'gregorian'} and
the date is after 1582-10-15). Otherwise, they are 'phony' datetime
objects which are actually instances of C{L{cftime.datetime}}. This is
because the python datetime module cannot handle the weird dates in some
calendars (such as C{'360_day'} and C{'all_leap'}) which don't exist in any real
world calendar.
Example usage:
>>> from cftime import utime
>>> from datetime import datetime
>>> cdftime = utime('hours since 0001-01-01 00:00:00')
>>> date = datetime.now()
>>> print date
2016-10-05 08:46:27.245015
>>>
>>> t = cdftime.date2num(date)
>>> print t
17669840.7742
>>>
>>> date = cdftime.num2date(t)
>>> print date
2016-10-05 08:46:27.244996
>>>
The resolution of the transformation operation is approximately a millisecond.
Warning: Dates between 1582-10-5 and 1582-10-15 do not exist in the
C{'standard'} or C{'gregorian'} calendars. An exception will be raised if you pass
a 'datetime-like' object in that range to the C{L{date2num}} class method.
Words of Wisdom from the British MetOffice concerning reference dates:
"udunits implements the mixed Gregorian/Julian calendar system, as
followed in England, in which dates prior to 1582-10-15 are assumed to use
the Julian calendar. Other software cannot be relied upon to handle the
change of calendar in the same way, so for robustness it is recommended
that the reference date be later than 1582. If earlier dates must be used,
it should be noted that udunits treats 0 AD as identical to 1 AD."
@ivar origin: datetime instance defining the origin of the netCDF time variable.
@ivar calendar: the calendar used (as specified by the C{calendar} keyword).
@ivar unit_string: a string defining the the netCDF time variable.
@ivar units: the units part of C{unit_string} (i.e. 'days', 'hours', 'seconds').
"""
def __init__(self, unit_string, calendar='standard',
only_use_cftime_datetimes=False):
"""
@param unit_string: a string of the form
C{'time-units since <time-origin>'} defining the time units.
Valid time-units are days, hours, minutes and seconds (the singular forms
are also accepted). An example unit_string would be C{'hours
since 0001-01-01 00:00:00'}. months is allowed as a time unit
*only* for the 360_day calendar.
@keyword calendar: describes the calendar used in the time calculations.
All the values currently defined in the U{CF metadata convention
<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
are accepted. The default is C{'standard'}, which corresponds to the mixed
Gregorian/Julian calendar used by the C{udunits library}. Valid calendars
are:
- C{'gregorian'} or C{'standard'} (default):
Mixed Gregorian/Julian calendar as defined by udunits.
- C{'proleptic_gregorian'}:
A Gregorian calendar extended to dates before 1582-10-15. That is, a year
is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
it is divisible by 400.
- C{'noleap'} or C{'365_day'}:
Gregorian calendar without leap years, i.e., all years are 365 days long.
- C{'all_leap'} or C{'366_day'}:
Gregorian calendar with every year being a leap year, i.e.,
all years are 366 days long.
-C{'360_day'}:
All years are 360 days divided into 30 day months.
-C{'julian'}:
Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
leap year if it is divisible by 4.
@keyword only_use_cftime_datetimes: if False (default), datetime.datetime
objects are returned from num2date where possible; if True dates which subclass
cftime.datetime are returned for all calendars.
@returns: A class instance which may be used for converting times from netCDF
units to datetime objects.
"""
calendar = calendar.lower()
if calendar in _calendars:
self.calendar = calendar
else:
raise ValueError(
"calendar must be one of %s, got '%s'" % (str(_calendars), calendar))
units, tzoffset, self.origin =\
_parse_date_and_units(unit_string,calendar)
# real-world calendars limited to positive reference years.
if self.calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
if self.origin.year == 0:
msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
raise ValueError(msg)
self.tzoffset = np.array(tzoffset,dtype=np.longdouble) # time zone offset in minutes
self.units = units
self.unit_string = unit_string
if self.calendar in ['noleap', '365_day'] and self.origin.month == 2 and self.origin.day == 29:
raise ValueError(
'cannot specify a leap day as the reference time with the noleap calendar')
if self.calendar == '360_day' and self.origin.day > 30:
raise ValueError(
'there are only 30 days in every month with the 360_day calendar')
self._jd0 = JulianDayFromDate(self.origin, calendar=self.calendar)
self.only_use_cftime_datetimes = only_use_cftime_datetimes
def date2num(self, date):
"""
Returns C{time_value} in units described by L{unit_string}, using
the specified L{calendar}, given a 'datetime-like' object.
The datetime object must represent UTC with no time-zone offset.
If there is a time-zone offset implied by L{unit_string}, it will
be applied to the returned numeric values.
Resolution is approximately a millisecond.
If C{calendar = 'standard'} or C{'gregorian'} (indicating
that the mixed Julian/Gregorian calendar is to be used), an
exception will be raised if the 'datetime-like' object describes
a date between 1582-10-5 and 1582-10-15.
Works for scalars, sequences and numpy arrays.
Returns a scalar if input is a scalar, else returns a numpy array.
"""
isscalar = False
try:
date[0]
except:
isscalar = True
if not isscalar:
date = np.array(date)
shape = date.shape
if isscalar:
jdelta = JulianDayFromDate(date, self.calendar)-self._jd0
else:
jdelta = JulianDayFromDate(date.flat, self.calendar)-self._jd0
if not isscalar:
jdelta = np.array(jdelta)
# convert to desired units, add time zone offset.
if self.units in microsec_units:
jdelta = jdelta * 86400. * 1.e6 + self.tzoffset * 60. * 1.e6
elif self.units in millisec_units:
jdelta = jdelta * 86400. * 1.e3 + self.tzoffset * 60. * 1.e3
elif self.units in sec_units:
jdelta = jdelta * 86400. + self.tzoffset * 60.
elif self.units in min_units:
jdelta = jdelta * 1440. + self.tzoffset
elif self.units in hr_units:
jdelta = jdelta * 24. + self.tzoffset / 60.
elif self.units in day_units:
jdelta = jdelta + self.tzoffset / 1440.
elif self.units in month_units and self.calendar == '360_day':
jdelta = jdelta/30. + self.tzoffset / (30. * 1440.)
else:
raise ValueError('unsupported time units')
if isscalar:
return jdelta.astype(np.float64)
else:
return np.reshape(jdelta.astype(np.float64), shape)
def num2date(self, time_value):
"""
Return a 'datetime-like' object given a C{time_value} in units
described by L{unit_string}, using L{calendar}.
dates are in UTC with no offset, even if L{unit_string} contains
a time zone offset from UTC.
Resolution is approximately a millisecond.
Works for scalars, sequences and numpy arrays.
Returns a scalar if input is a scalar, else returns a numpy array.
The datetime instances returned by C{num2date} are 'real' python datetime
objects if the date falls in the Gregorian calendar (i.e.
C{calendar='proleptic_gregorian'}, or C{calendar = 'standard'/'gregorian'} and
the date is after 1582-10-15). Otherwise, they are 'phony' datetime
objects which are actually instances of cftime.datetime. This is
because the python datetime module cannot handle the weird dates in some
calendars (such as C{'360_day'} and C{'all_leap'}) which
do not exist in any real world calendar.
"""
isscalar = False
try:
time_value[0]
except:
isscalar = True
ismasked = False
if np.ma.isMA(time_value) and np.ma.is_masked(time_value):
mask = time_value.mask
ismasked = True
if not isscalar:
time_value = np.array(time_value, dtype='d')
shape = time_value.shape
# convert to desired units, subtract time zone offset.
if self.units in microsec_units:
jdelta = time_value / 86400000000. - self.tzoffset / 1440.
elif self.units in millisec_units:
jdelta = time_value / 86400000. - self.tzoffset / 1440.
elif self.units in sec_units:
jdelta = time_value / 86400. - self.tzoffset / 1440.
elif self.units in min_units:
jdelta = time_value / 1440. - self.tzoffset / 1440.
elif self.units in hr_units:
jdelta = time_value / 24. - self.tzoffset / 1440.
elif self.units in day_units:
jdelta = time_value - self.tzoffset / 1440.
elif self.units in month_units and self.calendar == '360_day':
# only allowed for 360_day calendar
jdelta = time_value * 30. - self.tzoffset / 1440.
else:
raise ValueError('unsupported time units')
jd = self._jd0 + jdelta
if not isscalar:
if ismasked:
date = []
for j, m in zip(jd.flat, mask.flat):
if not m:
date.append(DateFromJulianDay(j, self.calendar,
self.only_use_cftime_datetimes))
else:
date.append(None)
else:
date = DateFromJulianDay(jd.flat, self.calendar,
self.only_use_cftime_datetimes)
else:
if ismasked and mask.item():
date = None
else:
date = DateFromJulianDay(jd, self.calendar,
self.only_use_cftime_datetimes)
if isscalar:
return date
else:
return np.reshape(np.array(date), shape)
cdef _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.
cpdef _parse_date(datestring):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string, assuming UTC
by default.
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"]),\
tzoffset_mins
cdef _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'):