File: cfdatetime.py

package info (click to toggle)
cf-python 1.3.2%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,996 kB
  • sloc: python: 51,733; ansic: 2,736; makefile: 78; sh: 2
file content (827 lines) | stat: -rw-r--r-- 20,229 bytes parent folder | download
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
import netCDF4

# Work: Running Sphinx v1.2b1
from datetime  import datetime

from numpy import array     as numpy_array
from numpy import ndarray   as numpy_ndarray
from numpy import ndim      as numpy_ndim
from numpy import vectorize as numpy_vectorize

from .functions    import inspect as cf_inspect
from .units        import Units

if netCDF4.__version__ <= '1.1.1':
    _netCDF4_netcdftime_parse_date = netCDF4.netcdftime._parse_date
    _netCDF4_netcdftime_strftime   = netCDF4.netcdftime._strftime
elif netCDF4.__version__ <= '1.2.4':
    _netCDF4_netcdftime_parse_date = netCDF4.netcdftime.netcdftime._parse_date
    _netCDF4_netcdftime_strftime   = netCDF4.netcdftime._datetime._strftime
else:
    import time

    def _findall(text, substr):
        # Also finds overlaps
        sites = []
        i = 0
        while 1:
            j = text.find(substr, i)
            if j == -1:
                break
            sites.append(j)
            i = j + 1
        return sites


    def _netCDF4_netcdftime_strftime(dt, fmt):
        if _illegal_s.search(fmt):
            raise TypeError("This strftime implementation does not handle %s")
        # don't use strftime method at all.
        # if dt.year > 1900:
        #    return dt.strftime(fmt)

        year = dt.year
        # For every non-leap year century, advance by
        # 6 years to get into the 28-year repeat cycle
        delta = 2000 - year
        off = 6 * (delta // 100 + delta // 400)
        year = year + off

        # Move to around the year 2000
        year = year + ((2000 - year) // 28) * 28
        timetuple = dt.timetuple()
        s1 = time.strftime(fmt, (year,) + timetuple[1:])
        sites1 = _findall(s1, str(year))

        s2 = time.strftime(fmt, (year + 28,) + timetuple[1:])
        sites2 = _findall(s2, str(year + 28))

        sites = []
        for site in sites1:
            if site in sites2:
                sites.append(site)

        s = s1
        syear = "%4d" % (dt.year,)
        for site in sites:
            s = s[:site] + syear + s[site + 4:]
        return s

    _netCDF4_netcdftime_parse_date = netCDF4.netcdftime._parse_date


# Define some useful units
_calendar_years  = Units('calendar_years')
_calendar_months = Units('calendar_months')

# ====================================================================
#
# Datetime object (overrides netCDF4.netcdftime.datetime)
#
# ====================================================================

class Datetime(object):

    # ----------------------------------------------------------------
    # Adapted from Jeff Whitaker's netCDF4.netcdftime.datetime
    # ----------------------------------------------------------------

    '''

A date-time object which supports CF calendars.

Any date and time valid in any CF calendar is allowed.

In many situations, it may be used interchangeably with a built-in
`datetime.datetime` object. For example:

>>> import datetime
>>> d = cf.Datetime(2004, 2, 30)
>>> d > datetime.datetime(2004, 2, 1)
True

**Attributes**

==============  ======================================================
Attribute       Description
==============  ======================================================
`!year`         The year of the date
`!month`        The month of the year of the date
`!day`          The day of the month of the date
`!hour`         The hour of the day of the date
`!minute`       The minute of the hour of the date
`!second`       The second of the minute of the date
`!microsecond`  The microsecond of the second of the date
==============  ======================================================

.. seealso:: `cf.dt`, `cf.TimeDuration`

'''
    def __init__(self, year, month=1, day=1, hour=0, minute=0, second=0,
                 microsecond=0, dayofwk=-1, dayofyr=1):
        '''**Initialization**

:Parameters:

    year: `int`
        The year.

    month, day, hour, minute, second, microsecond: `int`, optional
        The month of the year, the day of the month and time of the
        day. *month* and *day* default to 1 and *hour*; *minute*,
        *second* and *microsecond* default to 0.

:Examples:

>>> cf.Datetime(2003)
<CF Datetime: 2003-01-01 00:00:00>
>>> d = cf.Datetime(2003, 2, 30)
>>> d = cf.Datetime(2003, 2, 30, 0)
>>> d = cf.Datetime(2003, 2, 30, 0, 0)
>>> d = cf.Datetime(2003, 2, 30, 0, 0, 0)
>>> d = cf.Datetime(2003, 4, 5, 12, 30, 15)
>>> d = cf.Datetime(year=2003, month=4, day=5, hour=12, minute=30, second=15)
>>> d.year, d.month, d.day, d.hour, d.minute, d.second
(2003, 4, 5, 12, 30, 15)
>>> d.timetuple()
(2003, 4, 5, 12, 30, 15, -1, 1)

        '''
        # ------------------------------------------------------------
        # NOTE: dayofyr is set to 1 by default, otherwise
        # time.strftime will complain.
        # ------------------------------------------------------------
        self.year        = year
        self.month       = month
        self.day         = day
        self.hour        = hour
        self.minute      = minute
        self.second      = second
        self.microsecond = microsecond
        self.dayofwk     = dayofwk
        self.dayofyr     = dayofyr
        self.format      = '%Y-%m-%d %H:%M:%S'
    #--- End: def

    def __deepcopy__(self, memo):
        '''

Used if copy.deepcopy is called

''' 
        return self.copy()
    #--- End: def

    def __repr__(self):
        '''

x__repr__() <==> repr(x)

'''   
        return '<CF %s: %s>' % (self.__class__.__name__, self)
    #--- End: def

    def __str__(self):
        '''

x__str__() <==> str(x)

'''
        return self.strftime()
    #--- End: def

    def __eq__(self, other):
        '''

x__eq__(y) <==> x==y

'''
        try:
            return self._timetuple6() == other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def __ne__(self, other):
        '''

x__ne__(y) <==> x!=y

'''
        try:
            return self._timetuple6() != other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def __ge__(self, other):
        '''

x__ge__(y) <==> x>=y

'''
        try:
            return self._timetuple6() >= other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def __gt__(self, other):
        '''

x__gt__(y) <==> x>y

'''
        try:
            return self._timetuple6() > other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def __le__(self, other):
        '''

x__le__(y) <==> x<=y

'''
        try:
            return self._timetuple6() <= other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def __lt__(self, other):
        '''

x__lt__(y) <==> x<y

'''
        try:
            return self._timetuple6() < other.timetuple()[:6]
        except AttributeError:
            return NotImplemented
    #--- End: def

    def _to_real_datetime(self):
        return datetime(self.year, self.month, self.day,
                        self.hour, self.minute, self.second,
                        self.microsecond)
    #--- End: def

    def __hash__(self):
        try:
            d = self._to_real_datetime()
        except ValueError:
            return hash(self.timetuple())
        else:
            return hash(d)
    #--- End: def

#    @property
#    def year(self): return self._year
#
#    @property
#    def month(self): return self._month 
#        
#    @property
#    def day(self): return self._day         
#        
#    @property
#    def hour(self):return  self._hour       
#        
#    @property
#    def minute(self): return self._minute   
#        
#    @property
#    def second(self): return self._second   
#        
#    @property
#    def microsecond(self): return self._microsecond 
#        
#    @property
#    def dayofwk(self): return self._dayofwk    
#        
#    @property
#    def dayofyr(self): return self._dayofyr     
    
    def _timetuple6(self):
        '''

Return a tuple of the first six date-time attributes.

``d._timetuple6()`` is equivalent to ``(d.year, d.month, d.day,
d.hour, d.minute, d.second)``.

:Returns:

    out: `tuple`
        The first six date-time attributes.

:Examples:

>>> d = cf.Datetime(2005, 6, 7, 23, 45, 57)
>>> d._timetuple6()
(2005, 6, 7, 23, 45, 57)

'''
        return (self.year, self.month, self.day,
                self.hour, self.minute, self.second)
    #--- End: def

    def copy(self):
        '''

Return a deep copy.

``d.copy()`` is equivalent to ``copy.deepcopy(d)``.

:Returns:	

    out:
        The deep copy.

:Examples:

>>> e = d.copy()

'''
        return type(self)(*self.timetuple()[:-1])
    #--- End: def

    def inspect(self):
        '''

Inspect the attributes.

.. seealso:: `cf.inspect`

:Returns: 

    None

'''
        print cf_inspect(self)
    #--- End: def

    def strftime(self, format=None):
        if format is None:
            format = self.format
    
        return _netCDF4_netcdftime_strftime(self, format)
    #--- End: def

    def timetuple(self):
        '''

Return a tuple of the date-time attributes.

``d.timetuple()`` is equivalent to ``(d.year, d.month, d.day, d.hour,
d.minute, d.second, d.dayofwk, d.dayofyr, -1)``.

:Returns:

    out: `tuple`
        The date-time attributes.

:Examples:

>>> d = cf.Datetime(2005, 6, 7, 23, 45, 57, 999888)
>>> d.timetuple()
(2005, 6, 7, 23, 45, 57, -1, 1, -1)

'''
        return (self.year, self.month, self.day,
                self.hour, self.minute, self.second,
                self.dayofwk, self.dayofyr, -1)
    #--- End: def

    @classmethod
    def utcnow(cls):
        '''

Return the current Gregorian calendar UTC date and time.

:Returns:

    out: cf.Datetime
        The current UTC date and time.

:Examples:

>>> cf.Datetime.utcnow()
<CF Datetime: 2013-11-19 17:55:59>
>>> d = cf.Datetime(2005, 6, 7)
>>> d.utcnow()
<CF Datetime: 2013-11-19 17:56:07>
>>> d
<CF Datetime: 2005-06-07 00:00:00>

'''

        return cls(*datetime.utcnow().timetuple()[:-1])
    #--- End: def

#--- End: class
netCDF4.netcdftime.datetime = Datetime


def dt(*args, **kwargs):
    '''Return a date-time variable for a given date and time.

The date and time may be specified with an ISO 8601-like date-time
string (in which non-Gregorian calendar dates are allowed) or by
providing a value for the year and, optionally, the month, day, hour,
minute, second and microsecond.

.. seealso:: `cf.Datetime`

:Parameters:

    args, kwargs:
        If the first positional argument is a string, then it must be
        an ISO 8601-like date-time string from which a `cf.Datetime`
        object is initialized. Otherwise, the positional and keyword
        arguments are used to explicitly initialize a `cf.Datetime`
        object, so see `cf.Datetime` for details.

:Returns:

    out: `cf.Datetime`
        The new date-time object.

:Examples:

>>> d = cf.dt(2003, 2, 30)
>>> d = cf.dt(2003, 2, 30, 0, 0, 0)
>>> d = cf.dt('2003-2-30')
>>> d = cf.dt('2003-2-30 0:0:0')

>>> d = cf.dt(2003, 4, 5, 12, 30, 15)
>>> d = cf.dt(year=2003, month=4, day=5, hour=12, minute=30, second=15)
>>> d = cf.dt('2003-04-05 12:30:15')
>>> d.year, d.month, d.day, d.hour, d.minute, d.second
(2003, 4, 5, 12, 30, 15)

    '''
    if kwargs:
        return Datetime(*args, **kwargs)
    elif not args:
        raise ValueError("34 woah!")
    else:
        arg0 = args[0]
        if isinstance(arg0, basestring):
            return st2Datetime(arg0)
        elif isinstance(arg0, datetime):
            return Datetime(*arg0.timetuple()[:6])
        else:
            return Datetime(*args)
#--- End: def

def st2dt(array, units_in=None, dummy0=None, dummy1=None):
    '''
    
The returned array is always independent.

:Parameters:

    array: numpy array-like

    units_in: `cf.Units`, optional

    dummy0: optional
        Ignored.

    dummy1: optional
        Ignored.

:Returns: 

    out: `numpy.ndarray`
        An array of `cf.Datetime` or `datetime.datetime` objects with
        the same shape as *array*.

:Examples:

'''
    if getattr(units_in, '_calendar', None) in ('gregorian' 'standard', 'none'):
        return array_st2datetime(array)
    else:
        return array_st2Datetime(array)
#--- End: def

def st2datetime(date_string):
    '''

Parse an ISO 8601 date-time string into a datetime.datetime object.

:Parameters:

    date_string: `str`

:Returns:

    out: `datetime.datetime`

'''
    if date_string.count('-') != 2:
        raise ValueError("A string must contain a year, a month and a day")

    year,month,day,hour,minute,second,utc_offset = _netCDF4_netcdftime_parse_date(date_string)
    if utc_offset:
        raise ValueError("Can't specify a time offset from UTC")
            
    return datetime(year, month, day, hour, minute, second)
#--- End: def

array_st2datetime = numpy_vectorize(st2datetime, otypes=[object])

def st2Datetime(date_string):
    '''

Parse an ISO 8601 date-time string into a `cf.Datetime` object.

:Parameters:

    date_string: `str`

:Returns:

    out: `cf.Datetime`

'''
    if date_string.count('-') != 2:
        raise ValueError("A string must contain a year, a month and a day")

    year,month,day,hour,minute,second,utc_offset = _netCDF4_netcdftime_parse_date(date_string)
    if utc_offset:
        raise ValueError("Can't specify a time offset from UTC")
            
    return Datetime(year, month, day, hour, minute, second)
#--- End: def

array_st2Datetime = numpy_vectorize(st2Datetime, otypes=[object])

def rt2dt(array, units_in, dummy0=None, dummy1=None):
    '''

The returned array is always independent.

:Parameters:

    array: numpy array-like

    units_in: `cf.Units`

    dummy0:
        Ignored.

    dummy1:
        Ignored.

:Returns: 

    out: `numpy.ndarray`
        An array of `cf.Datetime` or `datetime.datetime` objects with
        the same shape as *array*.

'''           
    ndim = numpy_ndim(array)
    
    array = units_in._utime.num2date(array)
    if not ndim:
        array = numpy_array(array, dtype=object)

    return array
#--- End: def

def dt2rt(array, dummy0, units_out, dummy1=None):
    '''
    
The returned array is always independent.

:Parameters:

    array: numpy array-like of date-time objects

    dummy0:
        Ignored.

    units_out: `cf.Units`

    dummy1:
        Ignored.

:Returns: 

    out: `numpy.ndarray`
        An array of numbers with the same shape as *array*.

'''
    ndim = numpy_ndim(array)
    
    if not ndim and isinstance(array, numpy_ndarray):
        # This necessary because date2num gets upset if you pass
        # it a scalar numpy array
        array = array.item()

    array = units_out._utime.date2num(array)
    
    if not ndim:
        array = numpy_array(array)

    return array
#--- End: def

def st2rt(array, units_in, units_out, dummy1=None):
    '''
    
The returned array is always independent.

:Parameters:

    array: numpy array-like of ISO 8601 date-time strings

    units_in: `cf.Units` or `None`

    units_out: `cf.Units`

    dummy1:
        Ignored.

:Returns: 

    out: `numpy.ndarray`
        An array of floats with the same shape as *array*.

'''

    array = st2dt(array, units_in)

    ndim = numpy_ndim(array)
    
    if not ndim and isinstance(array, numpy_ndarray):
        # This necessary because date2num gets upset if you pass
        # it a scalar numpy array
        array = array.item()

    array = units_out._utime.date2num(array)
    
    if not ndim:
        array = numpy_array(array)

    return array
#--- End: def

def _JulianDayFromDate(date, calendar='standard'):
    '''

Create a Julian Day from a 'datetime-like' object.  Returns the
fractional Julian Day (resolution 1 second).

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.

Algorithm:

Meeus, Jean (1998) Astronomical Algorithms (2nd
Edition). Willmann-Bell, Virginia. p. 63

This is taken from netCDF4.netcdftime.JulianDayFromDate, with an error
check added.

'''
    # based on redate.py by David Finlayson.

    year=date.year; month=date.month; day=date.day
    hour=date.hour; minute=date.minute; second=date.second

    try:
        datetime(year, month, day, hour, minute, second)
    except ValueError:
        raise ValueError("Bad %s calendar date: %s" % (calendar, date))

    # Convert time to fractions of a day
    day = day + hour/24.0 + minute/1440.0 + second/86400.0

    # Start Meeus algorithm (variables are in his notation)
    if (month < 3):
        month = month + 12
        year = year - 1

    A = int(year/100)

    # MC
    # jd = int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + \
    #      day - 1524.5
    jd = 365.*year + int(0.25 * year + 2000.) + int(30.6001 * (month + 1)) + \
         day + 1718994.5

    # optionally adjust the jd for the switch from
    # the Julian to Gregorian Calendar
    # here assumed to have occurred the day after 1582 October 4
    if calendar in ['standard','gregorian']:
        if jd >= 2299170.5:
            # 1582 October 15 (Gregorian Calendar)
            B = 2 - A + int(A/4)
        elif jd < 2299160.5:
            # 1582 October 5 (Julian Calendar)
            B = 0
        else:
            raise ValueError('impossible date (falls in gap between end of Julian calendar and beginning of Gregorian calendar')
    elif calendar == 'proleptic_gregorian':
        B = 2 - A + int(A/4)
    elif calendar == 'julian':
        B = 0
    else:
        raise ValueError('unknown calendar, must be one of julian,standard,gregorian,proleptic_gregorian, got %s' % calendar)

    # adjust for Julian calendar if necessary
    jd = jd + B

    return jd
#--- End: def
netCDF4.netcdftime.JulianDayFromDate = _JulianDayFromDate

def _NoLeapDayFromDate(date):
    '''

Creates a Julian Day for a calendar with no leap years from a
date-time instance.  Returns the fractional Julian Day (resolution 1
second).

'''
    year=date.year; month=date.month; day=date.day
    hour=date.hour; minute=date.minute; second=date.second

    if month == 2 and day > 28:
        raise ValueError("Bad 365_day calendar date: %s" % date)

    if year != 0:
        try:
            datetime(year, month, day, hour, minute, second)
        except ValueError:
            raise ValueError("Bad 365_day calendar date: %s" % date)
    
    # Convert time to fractions of a day
    day = day + hour/24.0 + minute/1440.0 + second/86400.0

    # Start Meeus algorithm (variables are in his notation)
    if (month < 3):
        month = month + 12
        year = year - 1

    jd = int(365. * (year + 4716)) + int(30.6001 * (month + 1)) + \
         day - 1524.5

    return jd
#--- End: def

def interval(value, units_in, units_out=None, dummy1=None):
    '''
'''

    reftime = units_in.reftime.timetuple()
    
    if units == _calendar_years:
        months = value * 12
        int_months = int(months)
        if int_months != months:
            raise ValueError(
"Can't create a time interval of a non-integer number of calendar months: %s" % months)
    elif units == _calendar_months:
        months = value
        int_months = int(months)
        if int_months != months:
            raise ValueError(
"Can't create a time interval of a non-integer number of calendar months: %s" % months)
    else:
        int_months = None

    if int_months is not None:
        if value > 0:
            y, month1 = divmod(reftime[1] + int_months, 12)
            
            if not month1:
                y -= 1
                month1 = 12
                
            year1 = reftime[0] + y
        
            dt = Datetime(year1, month1, reftime[2:6])
        else:
            y, month0 = divmod(reftime[1] - int_months, 12)
            
            if not month0:
                y -= 1
                month0 = 12
                
            year0 = reftime[0] + y
            
            dt = Datetime(year0, month0, reftime[2:6])