Debian Codegraph @

test/test_cftime.py

raw
1 import cftime
2 from cftime import datetime as datetimex
3 from cftime import real_datetime
4 from cftime import (Datetime360Day, DatetimeAllLeap,
5 DatetimeGregorian, DatetimeJulian, DatetimeNoLeap,
6 DatetimeProlepticGregorian, DatetimeTAI, _parse_date,
7 date2index, date2num, num2date, UNIT_CONVERSION_FACTORS)
8 import copy
9 import unittest
10 import warnings
11 from collections import namedtuple
12 from datetime import datetime, timedelta, MINYEAR
13
14 import numpy as np
15 import pytest
16 from numpy.testing import assert_almost_equal, assert_equal
17
18 try:
19 from datetime import timezone
20 except ImportError: # python2.7
21 from datetime import tzinfo
22 class timezone(tzinfo):
23 """
24 Fixed offset in minutes east from UTC. adapted from
25 python 2.7 docs FixedOffset
26 """
27
28 def __init__(self, offset, name):
29 self.__offset = offset
30 self.__name = name
31
32 def utcoffset(self, dt):
33 return self.__offset
34
35 def tzname(self, dt):
36 return self.__name
37
38 def dst(self, dt):
39 return timedelta(hours=0)
40
41
42 # legacy class included here since tests use it.
43 class utime:
44 def __init__(self, unit_string, calendar='standard',
45 only_use_cftime_datetimes=True,
46 only_use_python_datetimes=False):
47 calendar = calendar.lower()
48 units, isostring = cftime._datesplit(unit_string)
49 self.origin = cftime._dateparse(unit_string,calendar=calendar)
50 self.units = units
51 self.calendar = calendar
52 self.unit_string = unit_string
53 self.only_use_cftime_datetimes = only_use_cftime_datetimes
54 self.only_use_python_datetimes = only_use_python_datetimes
55 def date2num(self, date):
56 return date2num(date,self.unit_string,calendar=self.calendar)
57 def num2date(self, time_value):
58 return num2date(time_value,self.unit_string,calendar=self.calendar,only_use_cftime_datetimes=self.only_use_cftime_datetimes,only_use_python_datetimes=self.only_use_python_datetimes)
59
60 utc = timezone(timedelta(hours=0), 'UTC')
61 est = timezone(timedelta(hours=-5), 'UTC')
62
63 # test cftime module for netCDF time <--> python datetime conversions.
64
65 dtime = namedtuple('dtime', ('values', 'units', 'calendar'))
66 dateformat = '%Y-%m-%d %H:%M:%S'
67 dateformat2 = '%y-%m-%d %H:%M:%S'
68
69 calendars=['standard', 'gregorian', 'proleptic_gregorian', 'noleap', 'julian',\
70 'all_leap', '365_day', '366_day', '360_day']
71 def adjust_calendar(calendar):
72 # check for and remove calendar synonyms.
73 calendar = calendar.lower()
74 if calendar == 'gregorian' or calendar == 'standard':
75 return 'standard'
76 elif calendar == 'noleap' or calendar == '365_day':
77 return 'noleap'
78 elif calendar == 'all_leap' or calendar == '366_day':
79 return 'all_leap'
80 else:
81 return calendar
82
83 class CFTimeVariable(object):
84 '''dummy "netCDF" variable to hold time info'''
85 def __init__(self, values, calendar='standard', units=None):
86
87 self.values = np.asarray(values)
88 self.calendar = calendar
89 self.units = units
90
91 def __array__(self):
92 # np special method that returns a np array.
93 return self.values[...]
94
95 def __getitem__(self, indexers):
96 return self.values[indexers]
97
98 def __repr__(self):
99 print('units: ', self.units)
100 print('calendar: ', self.calendar)
101 print('')
102 return repr(self.values)
103
104 def __str__(self):
105 return self.__repr__()
106
107 def __len__(self):
108 return len(self.values)
109
110 @property
111 def shape(self):
112 return self.values.shape
113
114
115 class cftimeTestCase(unittest.TestCase):
116
117 def setUp(self):
118 self.cdftime_mixed = utime('hours since 0001-01-01 00:00:00')
119 self.cdftime_julian = utime(
120 'hours since 0001-01-01 00:00:00', calendar='julian')
121 self.cdftime_mixed_tz = utime('hours since 0001-01-01 00:00:00 -06:00')
122 self.cdftime_pg = utime('seconds since 0001-01-01 00:00:00',
123 calendar='proleptic_gregorian')
124 self.cdftime_noleap = utime(
125 'days since 1600-02-28 00:00:00', calendar='noleap')
126 self.cdftime_leap = utime(
127 'days since 1600-02-29 00:00:00', calendar='all_leap')
128 self.cdftime_360day = utime(
129 'days since 1600-02-30 00:00:00', calendar='360_day')
130 self.cdftime_jul = utime(
131 'hours since 1000-01-01 00:00:00', calendar='julian')
132 self.cdftime_iso = utime("seconds since 1970-01-01T00:00:00Z")
133 self.cdftime_leading_space = utime("days since 850-01-01 00:00:00")
134 self.cdftime_mixed_capcal = utime('hours since 0001-01-01 00:00:00',
135 calendar='Standard')
136 self.cdftime_noleap_capcal = utime(
137 'days since 1600-02-28 00:00:00', calendar='NOLEAP')
138
139 def test_tz_aware(self):
140 """testing with timezone"""
141 self.assertTrue(self.cdftime_mixed.units == 'hours')
142 d1 = datetime(1582, 10, 4, 23, tzinfo=utc)
143 t1 = self.cdftime_mixed.date2num(d1)
144 d2 = datetime(1582, 10, 4, 18, tzinfo=est)
145 t2 = self.cdftime_mixed.date2num(d2)
146 assert_almost_equal(t1, 13865687.0)
147 assert_almost_equal(t2, 13865682.0) # est is 5 hours behind utc
148
149 def test_tz_naive(self):
150 """testing cftime"""
151 # test mixed julian/gregorian calendar
152 # check attributes.
153 self.assertTrue(self.cdftime_mixed.units == 'hours')
154 self.assertTrue(
155 str(self.cdftime_mixed.origin) == '0001-01-01 00:00:00')
156 self.assertTrue(
157 self.cdftime_mixed.unit_string == 'hours since 0001-01-01 00:00:00')
158 self.assertTrue(self.cdftime_mixed.calendar == 'standard')
159 # check date2num method. (date before switch)
160 d = datetime(1582, 10, 4, 23)
161 t1 = self.cdftime_mixed.date2num(d)
162 assert_almost_equal(t1, 13865687.0)
163 # check num2date method.
164 d2 = self.cdftime_mixed.num2date(t1)
165 self.assertTrue(str(d) == str(d2))
166 # this is a non-existent date, should raise ValueError.
167 d = datetime(1582, 10, 5, 0)
168 self.assertRaises(ValueError, self.cdftime_mixed.date2num, d)
169 # check date2num/num2date with date after switch.
170 d = datetime(1582, 10, 15, 0)
171 t2 = self.cdftime_mixed.date2num(d)
172 assert_almost_equal(t2, 13865688.0)
173 d2 = self.cdftime_mixed.num2date(t2)
174 self.assertTrue(str(d) == str(d2))
175 # check day of year.
176 ndayr = d.timetuple()[7]
177 self.assertTrue(ndayr == 288)
178 # test using np arrays.
179 t = np.arange(t2, t2 + 240.0, 12.)
180 t = np.reshape(t, (4, 5))
181 d = self.cdftime_mixed.num2date(t)
182 self.assertTrue(d.shape == t.shape)
183 d_check = "1582-10-15 00:00:001582-10-15 12:00:001582-10-16 00:00:001582-10-16 12:00:001582-10-17 00:00:001582-10-17 12:00:001582-10-18 00:00:001582-10-18 12:00:001582-10-19 00:00:001582-10-19 12:00:001582-10-20 00:00:001582-10-20 12:00:001582-10-21 00:00:001582-10-21 12:00:001582-10-22 00:00:001582-10-22 12:00:001582-10-23 00:00:001582-10-23 12:00:001582-10-24 00:00:001582-10-24 12:00:00"
184 d2 = [str(dd) for dd in d.flat]
185 self.assertTrue(d_check == ''.join(d2))
186 # test julian calendar with np arrays
187 d = self.cdftime_julian.num2date(t)
188 self.assertTrue(d.shape == t.shape)
189 d_check = "1582-10-05 00:00:001582-10-05 12:00:001582-10-06 00:00:001582-10-06 12:00:001582-10-07 00:00:001582-10-07 12:00:001582-10-08 00:00:001582-10-08 12:00:001582-10-09 00:00:001582-10-09 12:00:001582-10-10 00:00:001582-10-10 12:00:001582-10-11 00:00:001582-10-11 12:00:001582-10-12 00:00:001582-10-12 12:00:001582-10-13 00:00:001582-10-13 12:00:001582-10-14 00:00:001582-10-14 12:00:00"
190 d2 = [str(dd) for dd in d.flat]
191 self.assertTrue(d_check == ''.join(d2))
192 # test proleptic gregorian calendar.
193 self.assertTrue(self.cdftime_pg.units == 'seconds')
194 self.assertTrue(str(self.cdftime_pg.origin) == '0001-01-01 00:00:00')
195 self.assertTrue(
196 self.cdftime_pg.unit_string == 'seconds since 0001-01-01 00:00:00')
197 self.assertTrue(self.cdftime_pg.calendar == 'proleptic_gregorian')
198 # check date2num method.
199 d = datetime(1990, 5, 5, 2, 17)
200 t1 = self.cdftime_pg.date2num(d)
201 self.assertTrue(np.around(t1) == 62777470620.0)
202 # check num2date method.
203 d2 = self.cdftime_pg.num2date(t1)
204 self.assertTrue(d.strftime(dateformat) == d2.strftime(dateformat))
205 # make sure two digit years work in strftime (issue #362)
206 self.assertTrue(d.strftime(dateformat2) == d2.strftime(dateformat2))
207 # issue #401 (check for %y not y)
208 t = cftime.DatetimeGregorian(2026,4,14,0)
209 self.assertTrue(t.strftime('year=%Y') == 'year=2026')
210 # check day of year.
211 ndayr = d.timetuple()[7]
212 self.assertTrue(ndayr == 125)
213 # check noleap calendar.
214 # this is a non-existent date, should raise ValueError.
215 self.assertRaises(
216 ValueError, utime, 'days since 1600-02-29 00:00:00', calendar='noleap')
217 self.assertTrue(self.cdftime_noleap.units == 'days')
218 self.assertTrue(
219 str(self.cdftime_noleap.origin) == '1600-02-28 00:00:00')
220 self.assertTrue(
221 self.cdftime_noleap.unit_string == 'days since 1600-02-28 00:00:00')
222 self.assertTrue(self.cdftime_noleap.calendar == 'noleap')
223 assert_almost_equal(
224 self.cdftime_noleap.date2num(self.cdftime_noleap.origin), 0.0)
225 # check date2num method.
226 d1 = datetime(2000, 2, 28)
227 d2 = datetime(1600, 2, 28)
228 t1 = self.cdftime_noleap.date2num(d1)
229 t2 = self.cdftime_noleap.date2num(d2)
230 assert_almost_equal(t1, 400 * 365.)
231 assert_almost_equal(t2, 0.)
232 t12 = self.cdftime_noleap.date2num([d1, d2])
233 assert_almost_equal(t12, [400 * 365., 0])
234 # check num2date method.
235 d2 = self.cdftime_noleap.num2date(t1)
236 self.assertTrue(str(d1) == str(d2))
237 # check day of year.
238 ndayr = d2.timetuple()[7]
239 self.assertTrue(ndayr == 59)
240 # non-existent date, should raise ValueError.
241 date = datetime(2000, 2, 29)
242 self.assertRaises(ValueError, self.cdftime_noleap.date2num, date)
243 # check all_leap calendar.
244 self.assertTrue(self.cdftime_leap.units == 'days')
245 self.assertTrue(
246 str(self.cdftime_leap.origin) == '1600-02-29 00:00:00')
247 self.assertTrue(
248 self.cdftime_leap.unit_string == 'days since 1600-02-29 00:00:00')
249 self.assertTrue(self.cdftime_leap.calendar == 'all_leap')
250 assert_almost_equal(
251 self.cdftime_leap.date2num(self.cdftime_leap.origin), 0.0)
252 # check date2num method.
253 d1 = datetime(2000, 2, 29)
254 d2 = datetime(1600, 2, 29)
255 t1 = self.cdftime_leap.date2num(d1)
256 t2 = self.cdftime_leap.date2num(d2)
257 assert_almost_equal(t1, 400 * 366.)
258 assert_almost_equal(t2, 0.)
259 # check num2date method.
260 d2 = self.cdftime_leap.num2date(t1)
261 self.assertTrue(str(d1) == str(d2))
262 # check day of year.
263 ndayr = d2.timetuple()[7]
264 self.assertTrue(ndayr == 60)
265 # double check date2num,num2date methods.
266 d = datetime(2000, 12, 31)
267 t1 = self.cdftime_mixed.date2num(d)
268 d2 = self.cdftime_mixed.num2date(t1)
269 self.assertTrue(str(d) == str(d2))
270 ndayr = d2.timetuple()[7]
271 self.assertTrue(ndayr == 366)
272 # check 360_day calendar.
273 self.assertTrue(self.cdftime_360day.units == 'days')
274 self.assertTrue(
275 str(self.cdftime_360day.origin) == '1600-02-30 00:00:00')
276 self.assertTrue(
277 self.cdftime_360day.unit_string == 'days since 1600-02-30 00:00:00')
278 self.assertTrue(self.cdftime_360day.calendar == '360_day')
279 assert_almost_equal(
280 self.cdftime_360day.date2num(self.cdftime_360day.origin), 0.0)
281 # check date2num,num2date methods.
282 # use datetime from cftime, since this date doesn't
283 # exist in "normal" calendars.
284 d = datetimex(2000, 2, 30, calendar='')
285 t1 = self.cdftime_360day.date2num(d)
286 assert_almost_equal(t1, 360 * 400.)
287 d2 = self.cdftime_360day.num2date(t1)
288 assert_equal(str(d), str(d2))
289 # check day of year.
290 d = datetime(2001, 12, 30)
291 t = self.cdftime_360day.date2num(d)
292 assert_almost_equal(t, 144660.0)
293 date = self.cdftime_360day.num2date(t)
294 self.assertTrue(str(d) == str(date))
295 ndayr = date.timetuple()[7]
296 self.assertTrue(ndayr == 360)
297 # Check fraction
298 d = datetime(1969, 12, 30, 12)
299 t = self.cdftime_360day.date2num(d)
300 date = self.cdftime_360day.num2date(t)
301 assert_equal(str(d), str(date))
302 # test proleptic julian calendar.
303 d = datetime(1858, 11, 17, 12)
304 t = self.cdftime_jul.date2num(d)
305 assert_almost_equal(t, 7528932.0)
306 d1 = datetime(1582, 10, 4, 23)
307 d2 = datetime(1582, 10, 15, 0)
308 assert_almost_equal(
309 self.cdftime_jul.date2num(d1) + 241.0, self.cdftime_jul.date2num(d2))
310 date = self.cdftime_jul.num2date(t)
311 self.assertTrue(str(d) == str(date))
312 # test julian day from date, date from julian day
313 d = cftime.datetime(1858, 11, 17, calendar='standard')
314 # astronomical year numbering (with year zero)
315 dz = cftime.datetime(1858, 11, 17, calendar='standard',has_year_zero=True)
316 # toordinal (with fractional = True) is same as old JulianDayFromDate
317 mjd1 = d.toordinal(fractional=True)
318 mjd1z = dz.toordinal(fractional=True)
319 assert_almost_equal(mjd1, 2400000.5)
320 assert_almost_equal(mjd1z, 2400000.5)
321 # fromordinal (same as old DateFromJulianDay)
322 date1 = cftime.datetime.fromordinal(mjd1)
323 self.assertTrue(str(date1) == str(d))
324 # test iso 8601 units string
325 d = datetime(1970, 1, 1, 1)
326 t = self.cdftime_iso.date2num(d)
327 assert_equal(np.around(t), 3600)
328 # test fix for issue 75 (seconds hit 60 at end of month,
329 # day goes out of range).
330 t = 733499.0
331 d = num2date(t, units='days since 0001-01-01 00:00:00')
332 assert_equal(d.strftime(dateformat), '2009-04-01 00:00:00')
333 # test edge case of issue 75 for numerical problems
334 for t in (733498.999, 733498.9999, 733498.99999, 733498.999999, 733498.9999999):
335 d = num2date(t, units='days since 0001-01-01 00:00:00')
336 t2 = date2num(d, units='days since 0001-01-01 00:00:00')
337 assert abs(t2 - t) < 1e-5 # values should be less than second
338 # Check equality testing
339 d1 = datetimex(1979, 6, 21, 9, 23, 12, calendar='standard')
340 d2 = datetime(1979, 6, 21, 9, 23, 12)
341 assert d1 == d2
342 # check timezone offset
343 d = datetime(2012, 2, 29, 15)
344 # mixed_tz is -6 hours from UTC, mixed is UTC so
345 # difference in elapsed time is -6 hours.
346 assert self.cdftime_mixed_tz.date2num(
347 d) - self.cdftime_mixed.date2num(d) == -6
348
349 # Check comparisons with Python datetime types
350
351 # Note that d1 has to use the proleptic Gregorian calendar to
352 # be comparable to d2: datetime.datetime uses the proleptic
353 # Gregorian calendar and year 1000 is before the
354 # Julian/Gregorian transition (1582-10-15).
355 d1 = num2date(0, 'days since 1000-01-01', 'proleptic_gregorian')
356
357 d2 = datetime(2000, 1, 1)
358
359 # The date d3 is well after the Julian/Gregorian transition
360 # and so this Gregorian date can be compared to the proleptic
361 # Gregorian date d2.
362 d3 = num2date(0, 'days since 3000-01-01', 'standard')
363 assert d1 < d2
364 assert d2 < d3
365
366 # check all comparisons
367 assert d1 != d2
368 assert d1 <= d2
369 assert d2 > d1
370 assert d2 >= d1
371
372 # check datetime hash
373 d1 = datetimex(1995, 1, 1)
374 d2 = datetime(1995, 1, 1)
375 d3 = datetimex(2001, 2, 20)
376 assert hash(d1) == hash(d1)
377 assert hash(d1) == hash(d2)
378 assert hash(d1) != hash(d3)
379 assert hash(d3) == hash(d3)
380
381 # check datetime immutability
382 # using assertRaises as a context manager
383 # only works with python >= 2.7 (issue #497).
384 immutability_tests = {"year": 1999,
385 "month": 6,
386 "day": 5,
387 "hour": 10,
388 "minute": 33,
389 "second": 45,
390 "dayofwk": 1,
391 "dayofyr": 52,
392 "format": '%Y'}
393
394 for name, value in immutability_tests.items():
395 self.assertRaises(AttributeError, setattr, d1, name, value)
396
397 # Check leading white space
398 self.assertEqual(
399 str(self.cdftime_leading_space.origin), '0850-01-01 00:00:00')
400
401 #issue 330
402 units = "seconds since 1970-01-01T00:00:00Z"
403 t = utime(units)
404 for n in range(10):
405 assert n == int(round(t.date2num(t.num2date(n))))
406
407 #issue 344
408 units = 'hours since 2013-12-12T12:00:00'
409 assert 1.0 == date2num(num2date(1.0, units), units)
410
411 # test roundtrip accuracy
412 # also tests error found in issue #349
413 dateref = datetime(2015,2,28,12)
414 verbose = True # print out max error diagnostics
415 ntimes = 101
416 def roundtrip(delta,eps,units):
417 times1 = date2num(dateref,units,calendar=calendar)
418 times1 += delta*np.arange(0,ntimes)
419 dates1 = num2date(times1,units,calendar=calendar)
420 times2 = date2num(dates1,units,calendar=calendar)
421 dates2 = num2date(times2,units,calendar=calendar)
422 err = np.abs(times1 - times2)
423 assert np.all(err<eps)
424 dates1 = [date.strftime(dateformat) for date in dates1]
425 dates2 = [date.strftime(dateformat) for date in dates2]
426 assert dates1==dates2
427 return err.max()
428 for calendar in calendars:
429 eps = 1.
430 delta = 1.
431 units = 'microseconds since 2000-01-30 01:01:01'
432 maxerr = roundtrip(eps,delta,units)
433 if verbose:
434 print('calendar = %s max abs err (microsecs) = %s eps = %s' % \
435 (calendar,maxerr,eps))
436 eps = 0.001
437 delta = 0.001
438 units = 'milliseconds since 2000-01-30 01:01:01'
439 maxerr = roundtrip(eps,delta,units)
440 if verbose:
441 print('calendar = %s max abs err (millisecs) = %s eps = %s' % \
442 (calendar,maxerr,eps))
443 eps = 1.e-5
444 delta = 0.1
445 units = 'seconds since 0001-01-30 01:01:01'
446 maxerr = roundtrip(eps,delta,units)
447 if verbose:
448 print('calendar = %s max abs err (secs) = %s eps = %s' % \
449 (calendar,maxerr,eps))
450 eps = 1.e-6
451 delta = 0.01
452 units = 'minutes since 0001-01-30 01:01:01'
453 maxerr = roundtrip(eps,delta,units)
454 if verbose:
455 print('calendar = %s max abs err (mins) = %s eps = %s' % \
456 (calendar,maxerr,eps))
457 eps = 1.e-8
458 delta = 0.001
459 units = 'hours since 0001-01-30 01:01:01'
460 maxerr = roundtrip(eps,delta,units)
461 if verbose:
462 print('calendar = %s max abs err (hours) = %s eps = %s' % \
463 (calendar,maxerr,eps))
464 eps = 1.e-9
465 delta = 0.00001
466 units = 'days since 0001-01-30 01:01:01'
467 maxerr = roundtrip(eps,delta,units)
468 if verbose:
469 print('calendar = %s max abs err (days) = %s eps = %s' % \
470 (calendar,maxerr,eps))
471
472 # issue 353
473 assert num2date(0, 'hours since 2000-01-01 0') == datetime(2000,1,1,0)
474
475 # issue 354
476 num1 = np.array([[0, 1], [2, 3]])
477 num2 = np.array([[0, 1], [2, 3]])
478 dates1 = num2date(num1, 'days since 0001-01-01')
479 dates2 = num2date(num2, 'days since 2001-01-01')
480 assert dates1.shape == (2,2)
481 assert dates2.shape == (2,2)
482 num1b = date2num(dates1, 'days since 0001-01-01')
483 num2b = date2num(dates2, 'days since 2001-01-01')
484 assert num1b.shape == (2,2)
485 assert num2b.shape == (2,2)
486 assert_almost_equal(num1,num1b)
487 assert_almost_equal(num2,num2b)
488
489 # issue 357 (make sure time zone offset in units done correctly)
490 # Denver time, 7 hours behind UTC
491 units = 'hours since 1682-10-15 -07:00 UTC'
492 # date after gregorian switch, python datetime used
493 date = datetime(1682,10,15) # assumed UTC
494 num = date2num(date,units)
495 # UTC is 7 hours ahead of units, so num should be -7
496 assert num == -7
497 assert num2date(num, units) == date
498 units = 'hours since 1482-10-15 -07:00 UTC'
499 # date before gregorian switch, cftime datetime used
500 date = datetime(1482,10,15)
501 num = date2num(date,units)
502 date2 = num2date(num, units)
503 assert (num == -7)
504 assert (date2.year == date.year)
505 assert (date2.month == date.month)
506 assert (date2.day == date.day)
507 assert (date2.hour == date.hour)
508 assert (date2.minute == date.minute)
509 assert (date2.second == date.second)
510
511 # issue 362: case insensitive calendars
512 self.assertTrue(self.cdftime_mixed_capcal.calendar == 'standard')
513 self.assertTrue(self.cdftime_noleap_capcal.calendar == 'noleap')
514 d = datetime(2015, 3, 4, 12, 18, 30)
515 units = 'days since 0001-01-01'
516 for cap_cal, low_cal in (('STANDARD', 'standard'),
517 ('NoLeap', 'noleap'),
518 ('Standard', 'standard'),
519 ('ALL_LEAP', 'all_leap')):
520 d1 = date2num(d, units, cap_cal)
521 d2 = date2num(d, units, low_cal)
522 self.assertEqual(d1, d2)
523 self.assertEqual(num2date(d1, units, cap_cal),
524 num2date(d1, units, low_cal))
525 # issue 415
526 t = datetimex(2001, 12, 1, 2, 3, 4)
527 self.assertEqual(t, copy.deepcopy(t))
528
529 # issue 442
530 units = "days since 0000-01-01 00:00:00"
531 # this should fail (year zero not allowed with real-world calendars)
532 try:
533 date2num(datetime(1, 1, 1), units, calendar='standard')
534 except ValueError:
535 pass
536 # this should not fail (year zero allowed in 'fake' calendars)
537 t = date2num(datetime(1, 1, 1), units, calendar='360_day')
538 self.assertAlmostEqual(t,360)
539 d = num2date(t, units, calendar='360_day')
540 self.assertEqual(d, Datetime360Day(1,1,1))
541 d = num2date(0, units, calendar='360_day')
542 self.assertEqual(d, Datetime360Day(0,1,1))
543
544 # issue 685: wrong time zone conversion
545 # 'The following times all refer to the same moment: "18:30Z", "22:30+04", "1130-0700", and "15:00-03:30'
546 # (https://en.wikipedia.org/w/index.php?title=ISO_8601&oldid=787811367#Time_offsets_from_UTC)
547 # test num2date
548 utc_date = datetime(2000,1,1,18,30)
549 for units in ("hours since 2000-01-01 22:30+04:00", "hours since 2000-01-01 11:30-07:00", "hours since 2000-01-01 15:00-03:30"):
550 d = num2date(0, units, calendar="standard")
551 #self.assertEqual(d, utc_date)
552 # tolerance of 1.e-3 secs
553 assert np.abs((d-utc_date).total_seconds()) < 1.e-3
554 # also test with negative values to cover 2nd code path
555 d = num2date(-1, units, calendar="standard")
556 self.assertEqual(d, utc_date - timedelta(hours=1))
557
558 n = date2num(utc_date, units, calendar="standard")
559 # n should always be 0 as all units refer to the same point in time
560 self.assertEqual(n, 0)
561 # explicitly test 2nd code path for date2num
562 units = "hours since 2000-01-01 22:30+04:00"
563 n = date2num(utc_date, units, calendar="julian")
564 # n should always be 0 as all units refer to the same point in time
565 assert_almost_equal(n, 0)
566
567 # list around missing dates in mixed Julian/Gregorian calendar
568 # scalar
569 units = 'days since 0001-01-01 12:00:00'
570 t1 = date2num(datetime(1582, 10, 4), units, calendar='standard')
571 t2 = date2num(datetime(1582, 10, 15), units, calendar='standard')
572 self.assertEqual(t1+1, t2)
573 # list
574 t1, t2 = date2num([datetime(1582, 10, 4), datetime(1582, 10, 15)], units, calendar='standard')
575 self.assertEqual(t1+1, t2)
576 # this should fail: days missing in Gregorian calendar
577 try:
578 t1, t2, t3 = date2num([datetime(1582, 10, 4), datetime(1582, 10, 10), datetime(1582, 10, 15)], units, calendar='standard')
579 except ValueError:
580 pass
581 # test fix for issue #596 - julian day calculations wrong for negative years,
582 # caused incorrect roundtrip num2date(date2num(date)) roundtrip for dates with year
583 # < 0.
584 u = utime("seconds since 1-1-1",calendar='julian')
585 with warnings.catch_warnings():
586 warnings.simplefilter("ignore",category=cftime.CFWarning)
587 date1 = datetimex(-1, 1, 1)
588 with warnings.catch_warnings():
589 warnings.simplefilter("ignore",category=cftime.CFWarning)
590 date2 = u.num2date(u.date2num(date1))
591 assert (date2.year == date1.year)
592 assert (date2.month == date1.month)
593 assert (date2.day == date1.day)
594 assert (date2.hour == date1.hour)
595 assert (date2.minute == date1.minute)
596 assert (date2.second == date1.second)
597 assert_almost_equal(cftime.datetime.toordinal(date1,fractional=True), 1721057.5)
598 # issue 596 - negative years fail in utime.num2date
599 units="seconds since 1-1-1"
600 calendar="proleptic_gregorian"
601 yrzero=False
602 with warnings.catch_warnings():
603 warnings.simplefilter("ignore",category=cftime.CFWarning)
604 din=datetimex(-1,1,1,calendar=calendar,has_year_zero=yrzero)
605 d=num2date(date2num(din,units),units,calendar=calendar,has_year_zero=yrzero)
606 assert (d.year == -1)
607 assert (d.month == 1)
608 assert (d.day == 1)
609 assert (d.hour == 0)
610 # test fix for issue #659 (proper treatment of negative time values)
611 units = 'days since 1800-01-01 00:00:0.0'
612 d = num2date(-657073, units, calendar='standard')
613 assert (d.year == 1)
614 assert (d.month == 1)
615 assert (d.day == 1)
616 assert (d.hour == 0)
617 # cftime issue #134
618 d = num2date(-657071, units, calendar='proleptic_gregorian',
619 only_use_cftime_datetimes=False,only_use_python_datetimes=True)
620 assert d==datetime(1,1,1,0)
621 self.assertRaises(ValueError, num2date, \
622 -657072, units, calendar='proleptic_gregorian',
623 only_use_cftime_datetimes=False,only_use_python_datetimes=True)
624 # issue 685: wrong time zone conversion
625 # 'The following times all refer to the same moment: "18:30Z", "22:30+04", "1130-0700", and "15:00-03:30'
626 # (https://en.wikipedia.org/w/index.php?title=ISO_8601&oldid=787811367#Time_offsets_from_UTC)
627 # test num2date
628 utc_date = datetime(2000,1,1,18,30)
629 for units in ("hours since 2000-01-01 22:30+04:00", "hours since 2000-01-01 11:30-07:00", "hours since 2000-01-01 15:00-03:30"):
630 d = num2date(0, units, calendar="standard")
631 assert np.abs((d-utc_date).total_seconds()) < 1.e-3
632 # also test with negative values to cover 2nd code path
633 d = num2date(-1, units, calendar="standard")
634 assert np.abs((d - \
635 (utc_date-timedelta(hours=1))).total_seconds()) < 1.e-3
636
637 n = date2num(utc_date, units, calendar="standard")
638 # n should always be 0 as all units refer to the same point in time
639 self.assertEqual(n, 0)
640 # explicitly test 2nd code path for date2num
641 units = "hours since 2000-01-01 22:30+04:00"
642 n = date2num(utc_date, units, calendar="julian")
643 # n should always be 0 as all units refer to the same point in time
644 assert_almost_equal(n, 0)
645 # cftime issue #49
646 d = cftime.datetime.fromordinal(2450022.5, calendar="standard")
647 assert (d.year == 1995)
648 assert (d.month == 11)
649 assert (d.day == 1)
650 assert (d.hour == 0)
651 assert (d.minute == 0)
652 assert (d.second == 0)
653 # cftime issue #52
654 with warnings.catch_warnings():
655 warnings.simplefilter("ignore",category=cftime.CFWarning)
656 d = cftime.datetime.fromordinal(1684958.5,calendar='gregorian')
657 assert (d.year == -100)
658 assert (d.month == 3)
659 assert (d.day == 2)
660 assert (d.hour == 0)
661 assert (d.minute == 0)
662 assert (d.second == 0)
663 d = cftime.datetime.fromordinal(1684958.5,calendar='standard')
664 assert (d.year == -100)
665 assert (d.month == 3)
666 assert (d.day == 2)
667 assert (d.hour == 0)
668 assert (d.minute == 0)
669 assert (d.second == 0)
670 # test dayofwk, dayofyr attribute setting (cftime issue #13)
671 d1 = DatetimeGregorian(2020,2,29)
672 d2 = real_datetime(2020,2,29)
673 assert (d1.dayofwk == d2.dayofwk == 5)
674 assert (d1.dayofyr == d2.dayofyr == 60)
675 d1 = DatetimeGregorian(2020,2,29,23,59,59)
676 d2 = real_datetime(2020,2,29,23,59,59)
677 assert (d1.dayofwk == d2.dayofwk == 5)
678 assert (d1.dayofyr == d2.dayofyr == 60)
679 d1 = DatetimeGregorian(2020,2,28,23,59,59)
680 d2 = real_datetime(2020,2,28,23,59,59)
681 assert (d1.dayofwk == d2.dayofwk == 4)
682 assert (d1.dayofyr == d2.dayofyr == 59)
683 d1 = DatetimeGregorian(1700,1,1)
684 d2 = real_datetime(1700,1,1)
685 assert (d1.dayofwk == d2.dayofwk == 4)
686 assert (d1.dayofyr == d2.dayofyr == 1)
687 # last day of Julian Calendar (Thursday)
688 d1 = DatetimeJulian(1582, 10, 4, 12)
689 d2 = DatetimeGregorian(1582, 10, 4, 12)
690 assert (d1.dayofwk == d2.dayofwk == 3)
691 assert (d1.dayofyr == d2.dayofyr == 277)
692 # Monday in proleptic gregorian calendar
693 d1 = DatetimeProlepticGregorian(1582, 10, 4, 12)
694 d2 = real_datetime(1582,10,4,12)
695 assert (d1.dayofwk == d2.dayofwk == 0)
696 assert (d1.dayofyr == d2.dayofyr == 277)
697
698 # issue 173: Return the default values of dayofwk and dayofyr
699 # when calendar is ''
700 d1 = datetimex(1582, 10, 4, 12, calendar='')
701 assert (d1.dayofwk == d1.dayofyr == -1)
702 d1 = datetimex(2020, 5, 20, calendar='')
703 assert (d1.dayofwk == d1.dayofyr == -1)
704 d1 = datetimex(2020, 5, 20, dayofwk=-2, dayofyr=-3, calendar='')
705 assert (d1.dayofwk == -2)
706 assert (d1.dayofyr == -3)
707 d1 = datetimex(2020, 5, 20, dayofwk=8, dayofyr=9, calendar='')
708 assert (d1.dayofwk == 8)
709 assert (d1.dayofyr == 9)
710
711 # issue 71: negative reference years
712 # https://coastwatch.pfeg.noaa.gov/erddap/convert/time.html
713 # gives 2446433 (365 days more - is it counting year 0?)
714 # however http://aa.usno.navy.mil/data/docs/JulianDate.php gives
715 # 2446068, which agrees with us
716 with warnings.catch_warnings():
717 warnings.simplefilter("ignore",category=cftime.CFWarning)
718 units = "days since -4713-01-01T00:00:00Z"
719 t = date2num(datetime(1985,1,2), units, calendar="standard")
720 assert_almost_equal(t, 2446068)
721
722 # issue #68: allow months since for 360_day calendar
723 d = num2date(1, 'months since 0000-01-01 00:00:00', calendar='360_day')
724 self.assertEqual(d, Datetime360Day(0,2,1))
725 t = date2num(d, 'months since 0000-01-01 00:00:00', calendar='360_day')
726 self.assertEqual(t, 1)
727 # check that exception is raised if 'months since' used with
728 # anything but the 360_day calendar.
729 self.assertRaises(ValueError, num2date, \
730 1, 'months since 01-01-01',calendar='standard')
731 self.assertRaises(ValueError, utime, \
732 'months since 01-01-01', calendar='standard')
733 # issue #78 - extra digits due to roundoff
734 assert cftime.date2num(cftime.datetime(1, 12, 1, 0, 0, 0, 0, -1, 1), units='days since 01-01-01',calendar='noleap') == 334.0
735 assert cftime.date2num(cftime.num2date(1.0,units='days since 01-01-01',calendar='noleap'),units='days since 01-01-01',calendar='noleap') == 1.0
736 assert cftime.date2num(cftime.DatetimeNoLeap(1980, 1, 1, 0, 0, 0, 0, 6, 1),'days since 1970-01-01','noleap') == 3650.0
737 # issue #126
738 d = cftime.DatetimeProlepticGregorian(1, 1, 1)
739 assert cftime.date2num(d, 'days since 0001-01-01',\
740 'proleptic_gregorian') == 0.0
741 # issue #140 (fractional seconds in reference date)
742 d = datetime.strptime('2018-01-23 09:27:10.950000',"%Y-%m-%d %H:%M:%S.%f")
743 units = 'seconds since 2018-01-23 09:31:42.94'
744 assert float(cftime.date2num(d, units)) == -271.99
745 # issue 143 - same answer for arrays vs scalars.
746 units = 'seconds since 1970-01-01 00:00:00'
747 times_in = [1261440000.0, 1261440001.0, 1261440002.0, 1261440003.0,
748 1261440004.0, 1261440005.0]
749 times_out1 = cftime.num2date(times_in, units)
750 times_out2 = []
751 for time_in in times_in:
752 times_out2.append(cftime.num2date(time_in, units))
753 dates1 = [str(d) for d in times_out1]
754 dates2 = [str(d) for d in times_out2]
755 assert dates1 == dates2
756 # issue #143 formatting of microseconds
757 d = cftime.num2date(1261440000.015625,units)
758 # on windows only 100 ms precision
759 assert str(d)[0:24] == '2009-12-22 00:00:00.0156'
760 # issue #152 add isoformat()
761 assert d.isoformat()[0:24] == '2009-12-22T00:00:00.0156'
762 assert d.isoformat(sep=' ')[0:24] == '2009-12-22 00:00:00.0156'
763 assert d.isoformat(sep=' ',timespec='milliseconds') == '2009-12-22 00:00:00.016'
764 assert d.isoformat(sep=' ',timespec='seconds') == '2009-12-22 00:00:00'
765 assert d.isoformat(sep=' ',timespec='minutes') == '2009-12-22 00:00'
766 assert d.isoformat(sep=' ',timespec='hours') == '2009-12-22 00'
767 # issue #165: make sure python datetime returned
768 d=num2date(0,units="seconds since 2000-01-01 00:00:00",only_use_cftime_datetimes=False)
769 assert isinstance(d, datetime)
770 # issue #169: cftime.datetime has no calendar attribute, causing dayofwk,dayofyr methods
771 # to fail.
772 c = cftime.datetime(*cftime._parse_date('7480-01-01 00:00:00'),calendar='standard')
773 assert c.strftime() == '7480-01-01 00:00:00'
774 # issue #175: masked values not treated properly in num2date
775 times = np.ma.masked_array([-3956.7499999995343,-999999999999],mask=[False,True])
776 units='days since 1858-11-17 00:00:00'
777 dates = num2date(times, units=units, calendar='standard',\
778 only_use_cftime_datetimes=False, only_use_python_datetimes=True)
779 test = dates == np.ma.masked_array([datetime(1848, 1, 17, 6, 0, 0, 40), None],mask=[0,1])
780 assert test.all()
781 dates = num2date(times, units=units, calendar='standard')
782 assert str(dates)=="[cftime.DatetimeGregorian(1848, 1, 17, 6, 0, 0, 40, has_year_zero=False)\n --]"
783 # check that time range of 200,000 + years can be represented accurately
784 calendar='standard'
785 _MAX_INT64 = np.iinfo("int64").max
786 refdate = DatetimeGregorian(292277,10,24,0,0,1)
787 for unit in ['microseconds','milliseconds','seconds']:
788 units = '%s since 01-01-01' % unit
789 time = 292471*365*86400*(1000000//int(UNIT_CONVERSION_FACTORS[unit])) + 1000000//int(UNIT_CONVERSION_FACTORS[unit])
790 date = num2date(time,units,calendar=calendar)
791 assert date == refdate
792 # check round-trip
793 time2 = date2num(date,units,calendar=calendar)
794 date2 = num2date(time2,units,calendar=calendar)
795 # windows doesn't have a longdouble type (it defaults to float64)
796 if np.finfo(np.longdouble).precision == 18:
797 assert date2 == refdate
798 # microsecond roundtrip accuracy preserved over time ranges of 286 years
799 # (float64 can only represent integers exactly up to 2**53-1)
800 refdate=DatetimeGregorian(286,6,3,23,47,34,740992)
801 for unit in ['microseconds','milliseconds','seconds','hours','days']:
802 units = '%s since 01-01-01' % unit
803 time = (2**53 - 1)*(1/UNIT_CONVERSION_FACTORS[unit]) + 1/UNIT_CONVERSION_FACTORS[unit]
804 date = num2date(time,units,calendar=calendar)
805 assert date == refdate
806 # check round-trip
807 time2 = date2num(date,units,calendar=calendar)
808 date2 = num2date(time2,units,calendar=calendar)
809 assert date2 == refdate
810 # issue #185: date2num should work the numpy scalar array of dates (1.2.0 regression)
811 dates = np.array(datetime(2010, 2, 2, 0, 0))
812 assert (date2num(dates, units="hours since 2010-02-01 00:00:00") == 24.)
813 # issue #187 - roundtrip near second boundary
814 dt1 = datetime(1810, 4, 24, 16, 15, 10)
815 with warnings.catch_warnings():
816 warnings.simplefilter("ignore",category=cftime.CFWarning)
817 units = 'days since -4713-01-01 12:00'
818 dt2 = num2date(date2num(dt1, units), units, calendar='proleptic_gregorian')
819 dt2 = num2date(date2num(dt1, units, calendar='standard'), units)
820 assert dt1 == dt2
821 # issue #189 - leap years calculated incorrectly for negative years in proleptic_gregorian calendar
822 dt1 = datetime(2020, 4, 24, 16, 15, 10) # python datetime
823 units = 'days since -4713-01-01 12:00'
824 cal = 'proleptic_gregorian'
825 with warnings.catch_warnings():
826 warnings.simplefilter("ignore",category=cftime.CFWarning)
827 dt2 = num2date(date2num(dt1, units, cal, has_year_zero=False), units,
828 cal, has_year_zero=False)
829 assert dt1 == dt2
830 # issue #198 - cftime.datetime creates calendar specific datetimes that
831 # support addition/subtraction of timedeltas.
832 for cal in calendars:
833 dt = cftime.datetime(2020, 1, 1, calendar=cal)
834 dt += timedelta(hours=1)
835 assert str(dt) == '2020-01-01 01:00:00'
836 # issue #193 - years with more than four digits in reference date
837 assert cftime.date2num(cftime.datetime(18000, 12, 1, 0, 0), 'days since 18000-1-1', '360_day') == 330.0
838 # julian day not including year zero
839 d = cftime.datetime(2020, 12, 1, 12, calendar='julian')
840 with warnings.catch_warnings():
841 warnings.simplefilter("ignore",category=cftime.CFWarning)
842 units = 'days since -4713-1-1 12:00'
843 jd = cftime.date2num(d,units,calendar='julian')
844 assert jd == 2459198.0
845 # if calendar=None, use input date to determine calendar
846 jd = cftime.date2num(d,units,calendar=None)
847 assert jd == 2459198.0
848 # if no calendar specified, use calendar associated with datetime
849 # instance.
850 jd = cftime.date2num(d,units)
851 assert jd == 2459198.0
852 # use 'standard' calendar
853 jd = cftime.date2num(d,units,calendar='standard')
854 assert jd == 2459185.0
855
856 # issue #211
857 # (masked array handling in date2num - AttributeError:
858 # 'cftime._cftime.DatetimeGregorian' object has no attribute 'view')
859 m = np.ma.asarray(
860 [cftime.DatetimeGregorian(2014, 8, 1, 12, 0, 0, 0)]
861 )
862 assert (
863 cftime.date2num(m, units="seconds since 2000-1-1")==[4.602096e+08]
864 )
865
866 # test astronomical year numbering
867 jdref=2400000
868 with warnings.catch_warnings():
869 warnings.simplefilter("ignore",category=cftime.CFWarning)
870 for calendar in ['julian','standard','proleptic_gregorian']:
871 has_year_zero=False
872 try:
873 # this should raise ValueError
874 d = cftime.datetime(0,1,1,0,has_year_zero=has_year_zero,calendar=calendar)
875 except ValueError:
876 d = cftime.datetime(-1,1,1,0,has_year_zero=has_year_zero,calendar=calendar)
877 pass
878 else:
879 raise AssertionError # fail if ValueError not raised
880 d2 = cftime.datetime(1,1,1,0,has_year_zero=has_year_zero,calendar=calendar)
881 assert (d2-d).days==366 # 1-1-1 is 366 days after -1-1-1 if no year zero.
882 has_year_zero=True
883 d = cftime.datetime(0,1,1,0,has_year_zero=has_year_zero,calendar=calendar)
884 d2 = cftime.datetime(1,1,1,0,has_year_zero=has_year_zero,calendar=calendar)
885 assert (d2-d).days==366 # 1-1-1 is 366 days after 0-1-1 if year zero allowed.
886 for has_year_zero in [True,False]:
887 if calendar == 'julian':
888 d = cftime.datetime(1858,11, 4,12,has_year_zero=has_year_zero,calendar=calendar)
889 else:
890 d = cftime.datetime(1858,11,16,12,has_year_zero=has_year_zero,calendar=calendar)
891 if has_year_zero:
892 if calendar == 'proleptic_gregorian':
893 d0 = cftime.datetime(-4713,11,24,12,has_year_zero=has_year_zero,calendar=calendar)
894 else:
895 d0 = cftime.datetime(-4712, 1, 1,12,has_year_zero=has_year_zero,calendar=calendar)
896 else:
897 if calendar == 'proleptic_gregorian':
898 d0 = cftime.datetime(-4714,11,24,12,has_year_zero=has_year_zero,calendar=calendar)
899 else:
900 d0 = cftime.datetime(-4713, 1, 1,12,has_year_zero=has_year_zero,calendar=calendar)
901 jd = d.toordinal()
902 assert (d-d0).days == jdref
903 assert jd == jdref
904 assert d.toordinal() == jdref
905 d2 = cftime.datetime.fromordinal(jd,calendar=calendar,has_year_zero=has_year_zero)
906 assert d2 == d
907 # issue #248. Set has_year_zero=True if year zero requested
908 # on instance creation, or by using replace method.
909 d=cftime.datetime(0, 0, 0, calendar=None)
910 assert d.has_year_zero is True
911 d=cftime.datetime(1, 0, 0, calendar=None)
912 assert d.has_year_zero is False
913 d = d.replace(year=0)
914 assert d.has_year_zero is True
915 # this should raise a warning, since the default has_year_zero
916 # is changed if year specified as zero. (issue #248, PR #249)
917 self.assertWarns(UserWarning, cftime.datetime, 0, 1, 1,\
918 calendar='standard')
919 # check that for idealized calendars has_year_zero is always True
920 d=cftime.datetime(0, 1, 1, calendar='360_day')
921 assert d.has_year_zero is True
922 d=cftime.datetime(1, 1, 1, calendar='360_day')
923 assert d.has_year_zero is True
924 d = d.replace(year=0)
925 assert d.has_year_zero is True
926 # test leap year function
927 assert cftime.is_leap_year(2000,calendar='standard')
928 assert cftime.is_leap_year(-1,calendar='standard')
929 assert cftime.is_leap_year(0,calendar='standard',has_year_zero=True)
930 assert not cftime.is_leap_year(1,calendar='standard',has_year_zero=True)
931 assert not cftime.is_leap_year(1,calendar='365_day')
932 assert cftime.is_leap_year(1,calendar='366_day')
933 # num2date should not fail on an empty int array (issue #287)
934 d = cftime.num2date(np.array([], dtype="int64"), "days since 1970-01-01",\
935 calendar="proleptic_gregorian", only_use_cftime_datetimes=True)
936 # date2num should return an empty array if given one (issue #315)
937 d = cftime.date2num([], 'seconds since 2000-01-01 12:00:00')
938 assert d.size==0
939 # issue #328: handle nan/inf in num2date.
940 times = np.array([1,2,3,np.nan],dtype=np.float64)
941 expected = np.array([DatetimeGregorian(2000, 1, 2, 0, 0, 0, 0),
942 DatetimeGregorian(2000, 1, 3, 0, 0, 0, 0),
943 DatetimeGregorian(2000, 1, 4, 0, 0, 0, 0),
944 DatetimeGregorian(2000, 1, 5, 0, 0, 0, 0)])
945 mask = [False, False, False, True]
946 expected = np.ma.masked_array(expected, mask=mask)
947 result = cftime.num2date(times, 'days since 2000-01-01', 'standard')
948 np.testing.assert_equal(result, expected)
949 times = np.array([1,2,3,np.inf],dtype=np.float64)
950 result = cftime.num2date(times, 'days since 2000-01-01', 'standard')
951 np.testing.assert_equal(result, expected)
952 # issue #354: roundtrip not correct when dates are all python datetime
953 # instances and calendar not proleptic_gregorian.
954 datesin = np.array(["0002"],
955 dtype="datetime64[s]").astype("M8[us]").astype(datetime)
956 datein = datesin.item()
957 num = cftime.date2num(datein, "seconds since 2000-01-01", calendar='standard')
958 dateout = cftime.num2date(num, "seconds since 2000-01-01", calendar='standard')
959 dateout2 = cftime.datetime(datein.year, datein.month, datein.day,
960 calendar='standard')
961 assert(dateout==dateout2)
962
963
964 class TestDate2index(unittest.TestCase):
965
966 class TestTime:
967
968 """Fake a netCDF time variable."""
969
970 def __init__(self, start, n, step, units, calendar='standard'):
971 """Create an object that fakes a netCDF time variable.
972
973 Internally, this object has a _data array attribute whose values
974 corresponds to dates in the given units and calendar. `start`, `n`
975 and `step` define the starting date, the length of the array and
976 the distance between each date (in units).
977
978 """
979 self.units = units
980 self.calendar = calendar
981 t0 = date2num(start, units, calendar)
982 self._data = (t0 + np.arange(n) * step).astype('float')
983 self.dtype = float
984
985 def __getitem__(self, item):
986 return self._data[item]
987
988 def __len__(self):
989 return len(self._data)
990
991 def shape():
992 def fget(self):
993 return self._data.shape
994 return locals()
995
996 shape = property(**shape())
997
998 def setUp(self):
999 self.standardtime = self.TestTime(datetime(1950, 1, 1), 366, 24,
1000 'hours since 1900-01-01', 'standard')
1001
1002 self.issue272time = self.TestTime(datetime(1950, 1, 1), 5, 24,
1003 'hours since 1900-01-01', 'standard')
1004 self.issue272time._data=np.array([1053144, 1053150, 1053156, 1053157,
1005 1053162],np.int32)
1006 self.time_vars = {}
1007 self.time_vars['time'] = CFTimeVariable(
1008 values=self.standardtime,
1009 units='hours since 1900-01-01')
1010
1011 self.first_timestamp = datetime(2000, 1, 1)
1012 units = 'days since 1901-01-01'
1013 self.time_vars['time2'] = CFTimeVariable(
1014 values=date2num([self.first_timestamp], units),
1015 units=units)
1016
1017 ntimes = 21
1018
1019 units = "seconds since 1970-01-01 00:00:00"
1020 date = datetime(2037, 1, 1, 0)
1021 dates = [date]
1022 for ndate in range(ntimes-1):
1023 date += (ndate+1)*timedelta(hours=1)
1024 dates.append(date)
1025 self.time_vars['time3'] = CFTimeVariable(
1026 values=date2num(dates, units),
1027 units=units)
1028
1029 def test_tz_aware(self):
1030 """implicit test of date2num"""
1031 dutc = datetime(1950, 2, 1, 0, tzinfo=utc)
1032 t1 = date2index(dutc, self.standardtime)
1033 assert_equal(t1, 31)
1034 dest = datetime(1950, 1, 31, 19, tzinfo=est)
1035 t2 = date2index(dest, self.standardtime)
1036 assert_equal(t2, 31)
1037
1038 def test_simple(self):
1039 t = date2index(datetime(1950, 2, 1), self.standardtime)
1040 assert_equal(t, 31)
1041
1042 def test_singletime(self):
1043 # issue 215 test (date2index with time variable length == 1)
1044 time2 = self.time_vars['time2']
1045 result_index = date2index(self.first_timestamp, time2, select="exact")
1046 assert_equal(result_index, 0)
1047
1048 def test_list(self):
1049 t = date2index(
1050 [datetime(1950, 2, 1), datetime(1950, 2, 3)], self.standardtime)
1051 assert_equal(t, [31, 33])
1052
1053 def test_nonuniform(self):
1054 """Check that the fallback mechanism works. """
1055 nutime = self.TestTime(datetime(1950, 1, 1), 366, 24,
1056 'hours since 1900-01-01', 'standard')
1057
1058 # Let's remove the second entry, so that the computed stride is not
1059 # representative and the bisection method is needed.
1060 nutime._data = nutime._data[np.r_[0, slice(2, 200)]]
1061
1062 t = date2index(datetime(1950, 2, 1), nutime)
1063 assert_equal(t, 30)
1064
1065 t = date2index([datetime(1950, 2, 1), datetime(1950, 2, 3)], nutime)
1066 assert_equal(t, [30, 32])
1067
1068 def test_failure(self):
1069 nutime = self.TestTime(datetime(1950, 1, 1), 366, 24,
1070 'hours since 1900-01-01', 'standard')
1071 try:
1072 _t = date2index(datetime(1949, 2, 1), nutime)
1073 except ValueError:
1074 pass
1075 else:
1076 raise ValueError('This test should have failed.')
1077
1078 def test_select_dummy(self):
1079 calendar='standard'
1080 nutime = self.TestTime(datetime(1950, 1, 1), 366, 24,
1081 'hours since 1400-01-01', calendar)
1082
1083 dates = [datetimex(1950, 1, 2, 6, calendar=calendar), datetimex(
1084 1950, 1, 3, calendar=calendar), datetimex(1950, 1, 3, 18, calendar=calendar)]
1085
1086 t = date2index(dates, nutime, select='before')
1087 assert_equal(t, [1, 2, 2])
1088
1089 t = date2index(dates, nutime, select='after')
1090 assert_equal(t, [2, 2, 3])
1091
1092 t = date2index(dates, nutime, select='nearest')
1093 assert_equal(t, [1, 2, 3])
1094
1095 def test_select_nc(self):
1096 nutime = self.time_vars['time']
1097
1098 # these are python datetimes ('proleptic_gregorian' calendar).
1099 dates = [datetime(1950, 1, 2, 6), datetime(
1100 1950, 1, 3), datetime(1950, 1, 3, 18)]
1101
1102 t = date2index(dates, nutime, select='before')
1103 assert_equal(t, [1, 2, 2])
1104
1105 t = date2index(dates, nutime, select='after')
1106 assert_equal(t, [2, 2, 3])
1107
1108 t = date2index(dates, nutime, select='nearest')
1109 assert_equal(t, [1, 2, 3])
1110
1111 # Test dates outside the support with select
1112 t = date2index(datetime(1949, 12, 1), nutime, select='nearest')
1113 assert_equal(t, 0)
1114
1115 t = date2index(datetime(1978, 1, 1), nutime, select='nearest')
1116 assert_equal(t, 365)
1117
1118 # Test dates outside the support with before
1119 self.assertRaises(
1120 ValueError, date2index, datetime(1949, 12, 1), nutime, select='before')
1121
1122 t = date2index(datetime(1978, 1, 1), nutime, select='before')
1123 assert_equal(t, 365)
1124
1125 # Test dates outside the support with after
1126 t = date2index(datetime(1949, 12, 1), nutime, select='after')
1127 assert_equal(t, 0)
1128
1129 self.assertRaises(
1130 ValueError, date2index, datetime(1978, 1, 1), nutime, select='after')
1131 # test microsecond and millisecond units
1132 unix_epoch = "milliseconds since 1970-01-01T00:00:00Z"
1133 d = datetime(2038, 1, 19, 3, 14, 7)
1134 millisecs = int(
1135 date2num(d, unix_epoch, calendar='proleptic_gregorian'))
1136 assert_equal(millisecs, (2 ** 32 / 2 - 1) * 1000)
1137 unix_epoch = "microseconds since 1970-01-01T00:00:00Z"
1138 microsecs = int(date2num(d, unix_epoch))
1139 assert_equal(microsecs, (2 ** 32 / 2 - 1) * 1000000)
1140 # test microsecond accuracy in date2num/num2date roundtrip
1141 # note: microsecond accuracy lost for time intervals greater
1142 # than about 270 years.
1143 units = 'microseconds since 1776-07-04 00:00:00-12:00'
1144 dates = [datetime(1962, 10, 27, 6, 1, 30, 9001),
1145 datetime(1993, 11, 21, 12, 5, 25, 999),
1146 datetime(1995, 11, 25, 18, 7, 59, 9999)]
1147 times2 = date2num(dates, units)
1148 dates2 = num2date(times2, units)
1149 datediff = abs(dates-dates2)
1150 for diff in datediff:
1151 assert diff.microseconds < 100 # tolerance of 100 ms
1152
1153 def test_issue444(self):
1154 # make sure integer overflow not causing error in
1155 # calculation of nearest index when sum of adjacent
1156 # time values won't fit in 32 bits.
1157 query_time = datetime(2037, 1, 3, 21, 12)
1158 index = date2index(query_time, self.time_vars['time3'],
1159 select='nearest')
1160 assert index == 11
1161
1162 def test_issue272(self):
1163 timeArray = self.issue272time
1164 date = datetime(2020, 2, 22, 13)
1165 assert date2index(date, timeArray, calendar="gregorian",
1166 select="exact")==3
1167 assert date2index(date, timeArray, calendar="gregorian",
1168 select="before")==2
1169 assert date2index(date, timeArray, calendar="gregorian",
1170 select="after")==4
1171 assert date2index(date, timeArray, calendar="gregorian",
1172 select="nearest")==3
1173
1174
1175 class issue584TestCase(unittest.TestCase):
1176 """Regression tests for issue #584."""
1177 converters = None
1178
1179 def setUp(self):
1180 self.converters = {"360_day": utime("days since 1-1-1", "360_day"),
1181 "noleap": utime("days since 1-1-1", "365_day")}
1182
1183 def test_roundtrip(self):
1184 "Test roundtrip conversion (num2date <-> date2num) using 360_day and 365_day calendars."
1185
1186 for datetime_class in [Datetime360Day, DatetimeNoLeap]:
1187 # Pick a date and time outside of the range of the Julian calendar.
1188 date = datetime_class(-5000, 1, 1, 12)
1189
1190 converter = self.converters[date.calendar]
1191 self.assertEqual(date, converter.num2date(converter.date2num(date)))
1192
1193 def test_dayofwk(self):
1194 "Test computation of dayofwk in the 365_day calendar."
1195
1196 converter = self.converters["noleap"]
1197
1198 # Pick the date corresponding to the Julian day of 1.0 to test
1199 # the transition from positive to negative Julian days.
1200 with warnings.catch_warnings():
1201 warnings.simplefilter("ignore",category=cftime.CFWarning)
1202 julian_day = converter.date2num(datetimex(-4712, 1, 2, 12))
1203 # should be a Tuesday
1204
1205 old_date = converter.num2date(julian_day)
1206 for delta_year in range(1, 101): # 100 years cover several 7-year cycles
1207 date = converter.num2date(julian_day - delta_year * 365)
1208
1209 # test that the day of the week changes by one every year (except
1210 # for wrapping around every 7 years, of course)
1211 if date.dayofwk == 6:
1212 self.assertEqual(old_date.dayofwk, 0)
1213 else:
1214 self.assertEqual(old_date.dayofwk - date.dayofwk, 1)
1215
1216 old_date = date
1217
1218
1219 class DateTime(unittest.TestCase):
1220 def setUp(self):
1221 self.date1_365_day = DatetimeNoLeap(-5000, 1, 2, 12)
1222 self.date2_365_day = DatetimeNoLeap(-5000, 1, 3, 12)
1223 self.date3_gregorian = DatetimeGregorian(1969, 7, 20, 12)
1224 self.date3_gregorian_yearzero = DatetimeGregorian(1969, 7, 20, 12, has_year_zero=True)
1225 with warnings.catch_warnings():
1226 warnings.simplefilter("ignore",category=cftime.CFWarning)
1227 self.date4_proleptic_gregorian = cftime.datetime(-1,5,5,2,30,59,999999,calendar='proleptic_gregorian',has_year_zero=False)
1228 self.date4_julian = self.date4_proleptic_gregorian.change_calendar('julian',True)
1229
1230 # last day of the Julian calendar in the mixed Julian/Gregorian calendar
1231 self.date4_gregorian = DatetimeGregorian(1582, 10, 4)
1232 # first day of the Gregorian calendar in the mixed Julian/Gregorian calendar
1233 self.date5_gregorian = DatetimeGregorian(1582, 10, 15)
1234
1235 self.date6_proleptic_gregorian = DatetimeProlepticGregorian(1582, 10, 15)
1236
1237 self.date7_360_day = Datetime360Day(2000, 1, 1)
1238
1239 self.date8_julian = DatetimeJulian(1582, 10, 4)
1240
1241 # a datetime.datetime instance (proleptic Gregorian calendar)
1242 self.datetime_date1 = datetime(1969, 7, 21, 12)
1243
1244 self.delta = timedelta(hours=25)
1245
1246 def test_add(self):
1247 dt = self.date1_365_day
1248 # datetime + timedelta
1249 self.assertEqual(dt + self.delta, # add 25 hours
1250 dt.replace(day=dt.day + 1, hour=dt.hour + 1))
1251
1252 # timedelta + datetime
1253 self.assertEqual(self.delta + dt, # add 25 hours
1254 dt.replace(day=dt.day + 1, hour=dt.hour + 1))
1255
1256 # test the Julian/Gregorian transition
1257 self.assertEqual(self.date4_gregorian + self.delta,
1258 DatetimeGregorian(1582, 10, 15, 1))
1259
1260 # The Julian calendar has no invalid dates
1261 self.assertEqual(self.date8_julian + self.delta,
1262 DatetimeJulian(1582, 10, 5, 1))
1263
1264 # Test going over the year boundary.
1265 self.assertEqual(DatetimeGregorian(2000, 11, 1) + timedelta(days=30 + 31),
1266 DatetimeGregorian(2001, 1, 1))
1267
1268 # Year 2000 is a leap year.
1269 self.assertEqual(DatetimeGregorian(2000, 1, 1) + timedelta(days=31 + 29),
1270 DatetimeGregorian(2000, 3, 1))
1271
1272 # Test the 366_day calendar.
1273 self.assertEqual(DatetimeAllLeap(1, 1, 1) + timedelta(days=366 * 10 + 31),
1274 DatetimeAllLeap(11, 2, 1))
1275
1276 # The Gregorian calendar has no year zero.
1277 with warnings.catch_warnings():
1278 warnings.simplefilter("ignore",category=cftime.CFWarning)
1279 self.assertEqual(DatetimeGregorian(-1, 12, 31) + self.delta,
1280 DatetimeGregorian(1, 1, 1, 1))
1281
1282 def invalid_add_1():
1283 self.date1_365_day + 1
1284
1285 def invalid_add_2():
1286 1 + self.date1_365_day
1287
1288 for func in [invalid_add_1, invalid_add_2]:
1289 self.assertRaises(TypeError, func)
1290
1291 def test_sub(self):
1292 # subtracting a timedelta
1293 previous_day = self.date1_365_day - self.delta
1294 self.assertEqual(previous_day.day, self.date1_365_day.day - 1)
1295
1296 def total_seconds(td):
1297 """Equivalent to td.total_seconds() on Python >= 2.7. See
1298 https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
1299 """
1300 return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
1301
1302 # sutracting two cftime.datetime instances
1303 delta = self.date2_365_day - self.date1_365_day
1304 # date1 and date2 are exactly one day apart
1305 self.assertEqual(total_seconds(delta), 86400)
1306
1307 # subtracting cftime.datetime from datetime.datetime
1308 delta = self.datetime_date1 - self.date3_gregorian
1309 # real_date2 and real_date1 are exactly one day apart
1310 self.assertEqual(total_seconds(delta), 86400)
1311
1312 # subtracting datetime.datetime from cftime.datetime
1313 delta = self.date3_gregorian - self.datetime_date1
1314 # real_date2 and real_date1 are exactly one day apart
1315 self.assertEqual(total_seconds(delta), -86400)
1316
1317 # Test the Julian/Gregorian transition.
1318 self.assertEqual(self.date5_gregorian - self.delta,
1319 DatetimeGregorian(1582, 10, 3, 23))
1320
1321 # The proleptic Gregorian calendar does not have invalid dates.
1322 self.assertEqual(self.date6_proleptic_gregorian - self.delta,
1323 DatetimeProlepticGregorian(1582, 10, 13, 23))
1324
1325 with warnings.catch_warnings():
1326 warnings.simplefilter("ignore",category=cftime.CFWarning)
1327 # The Gregorian calendar has no year zero.
1328 self.assertEqual(DatetimeGregorian(1, 1, 1) - self.delta,
1329 DatetimeGregorian(-1, 12, 30, 23))
1330
1331 # The 360_day calendar has year zero.
1332
1333 self.assertEqual(self.date7_360_day - timedelta(days=2000 * 360),
1334 Datetime360Day(0, 1, 1))
1335
1336 # Test going over the year boundary.
1337 self.assertEqual(DatetimeGregorian(2000, 3, 1) - timedelta(days=29 + 31 + 31),
1338 DatetimeGregorian(1999, 12, 1))
1339
1340 # Year 2000 is a leap year.
1341 self.assertEqual(DatetimeGregorian(2000, 3, 1) - self.delta,
1342 DatetimeGregorian(2000, 2, 28, 23))
1343
1344 def invalid_sub_1():
1345 self.date1_365_day - 1
1346
1347 def invalid_sub_2():
1348 1 - self.date1_365_day
1349
1350 def invalid_sub_3():
1351 self.date1_365_day - self.datetime_date1
1352
1353 def invalid_sub_4():
1354 self.datetime_date1 - self.date1_365_day
1355
1356 def invalid_sub_5():
1357 self.date3_gregorian - self.date1_365_day
1358
1359 def invalid_sub_6():
1360 self.date3_gregorian - self.date3_gregorian_yearzero
1361
1362 for func in [invalid_sub_1, invalid_sub_2, invalid_sub_3, invalid_sub_4, invalid_sub_5, invalid_sub_6]:
1363 self.assertRaises(TypeError, func)
1364
1365 def test_replace(self):
1366 self.assertEqual(self.date1_365_day.replace(year=4000).year, 4000)
1367 self.assertEqual(self.date1_365_day.replace(month=3).month, 3)
1368 self.assertEqual(self.date1_365_day.replace(day=3).day, 3)
1369 self.assertEqual(self.date1_365_day.replace(hour=3).hour, 3)
1370 self.assertEqual(self.date1_365_day.replace(minute=3).minute, 3)
1371 self.assertEqual(self.date1_365_day.replace(second=3).second, 3)
1372 self.assertEqual(self.date1_365_day.replace(microsecond=3).microsecond, 3)
1373 d = datetimex(2000, 2, 3, calendar='noleap')
1374 self.assertEqual(d.replace(year=1999).calendar, 'noleap')
1375 d = datetimex(2000, 2, 3, calendar='')
1376 self.assertEqual(d.replace(year=1999).calendar, '')
1377
1378 def test_pickling(self):
1379 "Test reversibility of pickling."
1380 import pickle
1381
1382 date = Datetime360Day(year=1, month=2, day=3, hour=4, minute=5, second=6, microsecond=7)
1383 deserialized = pickle.loads(pickle.dumps(date))
1384 self.assertEqual(date, deserialized)
1385 self.assertEqual(type(date), type(deserialized))
1386
1387 date = datetimex(1, 2, 3, 4, 5, 6, 7, calendar="360_day")
1388 deserialized = pickle.loads(pickle.dumps(date))
1389 self.assertEqual(date, deserialized)
1390 self.assertEqual(type(date), type(deserialized))
1391
1392 def test_misc(self):
1393 "Miscellaneous tests."
1394 # make sure repr succeeds
1395 repr(self.date1_365_day)
1396
1397 # make sure strftime without a format string works
1398 self.assertEqual(self.date3_gregorian.strftime(None),
1399 "1969-07-20 12:00:00")
1400
1401 def invalid_year():
1402 with warnings.catch_warnings():
1403 warnings.simplefilter("ignore",category=cftime.CFWarning)
1404 DatetimeGregorian(0, 1, 1, has_year_zero=False) + self.delta
1405
1406 def invalid_month():
1407 DatetimeGregorian(1, 13, 1) + self.delta
1408
1409 def invalid_day():
1410 DatetimeGregorian(1, 1, 32) + self.delta
1411
1412 def invalid_gregorian_date():
1413 DatetimeGregorian(1582, 10, 5) + self.delta
1414
1415 for func in [invalid_year, invalid_month, invalid_day, invalid_gregorian_date]:
1416 self.assertRaises(ValueError, func)
1417
1418 def test_richcmp(self):
1419 # compare datetime and datetime
1420 self.assertTrue(self.date1_365_day == self.date1_365_day)
1421 self.assertFalse(self.date1_365_day == self.date2_365_day)
1422 self.assertTrue(self.date1_365_day < self.date2_365_day)
1423 self.assertFalse(self.date1_365_day < self.date1_365_day)
1424 self.assertTrue(self.date2_365_day > self.date1_365_day)
1425 self.assertFalse(self.date1_365_day > self.date2_365_day)
1426 # compare real_datetime and datetime
1427 self.assertTrue(self.datetime_date1 > self.date3_gregorian)
1428 # compare datetime and real_datetime
1429 self.assertFalse(self.date3_gregorian > self.datetime_date1)
1430 # compare different calendars (uses change_calendar method)
1431 self.assertTrue(self.date3_gregorian_yearzero == self.date3_gregorian)
1432 self.assertTrue(self.date4_proleptic_gregorian == self.date4_julian)
1433
1434 def not_comparable_1():
1435 "compare two datetime instances with different calendars"
1436 self.date1_365_day > self.date3_gregorian
1437
1438 def not_comparable_2():
1439 "compare a datetime instance with a non-standard calendar to real_datetime"
1440 self.date2_365_day > self.datetime_date1
1441
1442 def not_comparable_3():
1443 "compare datetime.datetime to cftime.datetime with a non-gregorian calendar"
1444 self.datetime_date1 > self.date2_365_day
1445
1446 def not_comparable_4():
1447 "compare a datetime instance to non-datetime"
1448 self.date1_365_day > 0
1449
1450 def not_comparable_5():
1451 "compare non-datetime to a datetime instance"
1452 0 < self.date1_365_day
1453
1454 for func in [not_comparable_1, not_comparable_2, not_comparable_3, not_comparable_4, not_comparable_5]:
1455 self.assertRaises(TypeError, func)
1456
1457 class issue17TestCase(unittest.TestCase):
1458 """Regression tests for issue #17/#669."""
1459 # issue 17 / 699: timezone formats not supported correctly
1460 # valid timezone formats are: +-hh, +-hh:mm, +-hhmm
1461
1462 def setUp(self):
1463 pass
1464
1465 def test_parse_date_tz(self):
1466 "Test timezone parsing in _parse_date"
1467
1468 # these should succeed and are ISO8601 compliant
1469 expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 60.0)
1470 for datestr in ("2017-05-01 00:00+01:00", "2017-05-01 00:00+0100", "2017-05-01 00:00+01"):
1471 d = _parse_date(datestr)
1472 assert_equal(d, expected_parsed_date)
1473 # some more tests with non-zero minutes, should all be ISO compliant and work
1474 expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 85.0)
1475 for datestr in ("2017-05-01 00:00+01:25", "2017-05-01 00:00+0125"):
1476 d = _parse_date(datestr)
1477 assert_equal(d, expected_parsed_date)
1478 # these are NOT ISO8601 compliant and should not even be parseable but will be parsed with timezone anyway
1479 # because, due to support of other legacy time formats, they are difficult to reject
1480 # ATTENTION: only the hours part of this will be parsed, single-digit minutes will be ignored!
1481 expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 60.0)
1482 for datestr in ("2017-05-01 00:00+01:0", "2017-05-01 00:00+01:", "2017-05-01 00:00+01:5"):
1483 d = _parse_date(datestr)
1484 assert_equal(d, expected_parsed_date)
1485 # these should not even be parseable as datestrings but are parseable anyway with ignored timezone
1486 # this is because the module also supports some legacy, non-standard time strings
1487 expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 0.0)
1488 for datestr in ("2017-05-01 00:00+1",):
1489 d = _parse_date(datestr)
1490 assert_equal(d, expected_parsed_date)
1491
1492
1493 class issue57TestCase(unittest.TestCase):
1494 """Regression tests for issue #57."""
1495 # issue 57: cftime._cftime._dateparse returns quite opaque error messages that make it difficult to
1496 # track down the source of problem
1497 def setUp(self):
1498 pass
1499
1500 def test_parse_incorrect_unitstring(self):
1501 for datestr in ("days since2017-05-01 ", "dayssince 2017-05-01 00:00", "days snce 2017-05-01 00:00", "days_since_2017-05-01 00:00",
1502 "days_since_2017-05-01_00:00"):
1503 self.assertRaises(
1504 ValueError, cftime._cftime._dateparse, datestr, 'standard')
1505
1506 self.assertRaises(
1507 ValueError, cftime._cftime.num2date, 1, datestr, 'standard')
1508
1509 self.assertRaises(
1510 ValueError, cftime._cftime.date2num, datetime(1900, 1, 1, 0), datestr, 'standard')
1511
1512
1513 _DATE_TYPES = [DatetimeNoLeap, DatetimeAllLeap, DatetimeJulian, Datetime360Day,
1514 DatetimeGregorian, DatetimeProlepticGregorian]
1515
1516
1517 @pytest.fixture(params=_DATE_TYPES)
1518 def date_type(request):
1519 return request.param
1520
1521
1522 @pytest.fixture(params=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
1523 def month(request):
1524 return request.param
1525
1526
1527 @pytest.fixture
1528 def days_per_month_non_leap_year(date_type, month):
1529 if date_type is Datetime360Day:
1530 return [-1, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30][month]
1531 if date_type is DatetimeAllLeap:
1532 return [-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
1533 else:
1534 return [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
1535
1536
1537 @pytest.fixture
1538 def days_per_month_leap_year(date_type, month):
1539 if date_type is Datetime360Day:
1540 return [-1, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30][month]
1541 if date_type in [DatetimeGregorian, DatetimeProlepticGregorian,
1542 DatetimeJulian, DatetimeAllLeap]:
1543 return [-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
1544 else:
1545 return [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
1546
1547
1548 def test_zero_year(date_type):
1549 # Year 0 is valid in the 360,365 and 366 day and
1550 # Proleptic Gregorian calendars by default.
1551 with warnings.catch_warnings():
1552 warnings.simplefilter("ignore",category=cftime.CFWarning)
1553 if date_type in [DatetimeNoLeap, DatetimeAllLeap, Datetime360Day,
1554 DatetimeProlepticGregorian]:
1555 date_type(0, 1, 1)
1556 else:
1557 d=date_type(0,1,1) # has_year_zero=True set if year 0 specified
1558 assert d.has_year_zero # (issue #248)
1559 with pytest.raises(ValueError):
1560 date_type(0, 1, 1, has_year_zero=False)
1561
1562
1563 def test_invalid_month(date_type):
1564 with pytest.raises(ValueError):
1565 date_type(1, 0, 1)
1566
1567 with pytest.raises(ValueError):
1568 date_type(1, 13, 1)
1569
1570
1571 def test_invalid_day_non_leap_year(
1572 date_type, month, days_per_month_non_leap_year):
1573 with pytest.raises(ValueError):
1574 date_type(1, month, days_per_month_non_leap_year + 1)
1575
1576
1577 def test_invalid_day_leap_year(date_type, month, days_per_month_leap_year):
1578 with pytest.raises(ValueError):
1579 date_type(2000, month, days_per_month_leap_year + 1)
1580
1581
1582 def test_invalid_day_lower_bound(date_type, month):
1583 with pytest.raises(ValueError):
1584 date_type(1, month, 0)
1585
1586
1587 def test_valid_day_non_leap_year(
1588 date_type, month, days_per_month_non_leap_year):
1589 date_type(1, month, 1)
1590 date_type(1, month, days_per_month_non_leap_year)
1591
1592
1593 def test_valid_day_leap_year(
1594 date_type, month, days_per_month_leap_year):
1595 date_type(2000, month, 1)
1596 date_type(2000, month, days_per_month_leap_year)
1597
1598
1599 _INVALID_SUB_DAY_TESTS = {
1600 'lower-bound-hour': (1, 1, 1, -1),
1601 'upper-bound-hour': (1, 1, 1, 24),
1602 'lower-bound-minute': (1, 1, 1, 1, -1),
1603 'upper-bound-minute': (1, 1, 1, 1, 60),
1604 'lower-bound-second': (1, 1, 1, 1, 1, -1),
1605 'upper-bound-second': (1, 1, 1, 1, 1, 60),
1606 'lower-bound-microsecond': (1, 1, 1, 1, 1, 1, -1),
1607 'upper-bound-microsecond': (1, 1, 1, 1, 1, 1, 1000000)
1608 }
1609
1610
1611 @pytest.mark.parametrize('date_args', list(_INVALID_SUB_DAY_TESTS.values()),
1612 ids=list(_INVALID_SUB_DAY_TESTS.keys()))
1613 def test_invalid_sub_day_reso_dates(date_type, date_args):
1614 with pytest.raises(ValueError):
1615 date_type(*date_args)
1616
1617
1618 _VALID_SUB_DAY_TESTS = {
1619 'lower-bound-hour': (1, 1, 1, 0),
1620 'upper-bound-hour': (1, 1, 1, 23),
1621 'lower-bound-minute': (1, 1, 1, 1, 0),
1622 'upper-bound-minute': (1, 1, 1, 1, 59),
1623 'lower-bound-second': (1, 1, 1, 1, 1, 0),
1624 'upper-bound-second': (1, 1, 1, 1, 1, 59),
1625 'lower-bound-microsecond': (1, 1, 1, 1, 1, 1, 0),
1626 'upper-bound-microsecond': (1, 1, 1, 1, 1, 1, 999999)
1627 }
1628
1629
1630 @pytest.mark.parametrize('date_args', list(_VALID_SUB_DAY_TESTS.values()),
1631 ids=list(_VALID_SUB_DAY_TESTS.keys()))
1632 def test_valid_sub_day_reso_dates(date_type, date_args):
1633 date_type(*date_args)
1634
1635
1636 @pytest.mark.parametrize(
1637 'date_args',
1638 [(1582, 10, 5), (1582, 10, 14)], ids=['lower-bound', 'upper-bound'])
1639 def test_invalid_julian_gregorian_mixed_dates(date_type, date_args):
1640 if date_type is DatetimeGregorian:
1641 with pytest.raises(ValueError):
1642 date_type(*date_args)
1643 else:
1644 date_type(*date_args)
1645
1646
1647 @pytest.mark.parametrize(
1648 'date_args',
1649 [(1582, 10, 4), (1582, 10, 15)], ids=['lower-bound', 'upper-bound'])
1650 def test_valid_julian_gregorian_mixed_dates(date_type, date_args):
1651 date_type(*date_args)
1652
1653
1654 @pytest.mark.parametrize(
1655 'date_args',
1656 [(1, 2, 3, 4, 5, 6), (10, 2, 3, 4, 5, 6), (100, 2, 3, 4, 5, 6),
1657 (1000, 2, 3, 4, 5, 6),
1658 (2000, 1, 1, 12, 34, 56, 123456)],
1659 ids=['1', '10', '100', '1000', '2000'])
1660 def test_str_matches_datetime_str(date_type, date_args):
1661 assert str(date_type(*date_args)) == str(datetime(*date_args))
1662
1663
1664 _EXPECTED_DATE_TYPES = {'noleap': DatetimeNoLeap,
1665 '365_day': DatetimeNoLeap,
1666 '360_day': Datetime360Day,
1667 'julian': DatetimeJulian,
1668 'all_leap': DatetimeAllLeap,
1669 '366_day': DatetimeAllLeap,
1670 'gregorian': DatetimeGregorian,
1671 'proleptic_gregorian': DatetimeProlepticGregorian,
1672 'standard': DatetimeGregorian}
1673
1674
1675 @pytest.mark.parametrize(
1676 ['calendar', 'expected_date_type'],
1677 list(_EXPECTED_DATE_TYPES.items())
1678 )
1679 def test_num2date_only_use_cftime_datetimes_negative_years(
1680 calendar, expected_date_type):
1681 with warnings.catch_warnings():
1682 warnings.simplefilter("ignore",category=cftime.CFWarning)
1683 result = num2date(-1000., units='days since 0001-01-01', calendar=calendar,
1684 only_use_cftime_datetimes=True)
1685 assert isinstance(result, datetimex)
1686 assert (result.calendar == adjust_calendar(calendar))
1687
1688
1689 @pytest.mark.parametrize(
1690 ['calendar', 'expected_date_type'],
1691 list(_EXPECTED_DATE_TYPES.items())
1692 )
1693 def test_num2date_only_use_cftime_datetimes_pre_gregorian(
1694 calendar, expected_date_type):
1695 result = num2date(1., units='days since 0001-01-01', calendar=calendar,
1696 only_use_cftime_datetimes=True)
1697 assert isinstance(result, datetimex)
1698 assert (result.calendar == adjust_calendar(calendar))
1699
1700
1701 @pytest.mark.parametrize(
1702 ['calendar', 'expected_date_type'],
1703 list(_EXPECTED_DATE_TYPES.items())
1704 )
1705 def test_num2date_only_use_cftime_datetimes_post_gregorian(
1706 calendar, expected_date_type):
1707 result = num2date(0., units='days since 1582-10-15', calendar=calendar,
1708 only_use_cftime_datetimes=True)
1709 assert isinstance(result, datetimex)
1710 assert (result.calendar == adjust_calendar(calendar))
1711
1712
1713 def test_repr():
1714 expected = "cftime.datetime(2000, 1, 1, 0, 0, 0, 0, calendar='standard', has_year_zero=False)"
1715 assert repr(datetimex(2000, 1, 1, calendar='standard')) == expected
1716 expected = "cftime.datetime(2000, 1, 1, 0, 0, 0, 0, calendar='', has_year_zero=False)"
1717 assert repr(datetimex(2000, 1, 1, calendar=None)) == expected
1718
1719 def test_string_format():
1720 dt = cftime.datetime(2000, 1, 1)
1721 # check the default formatting is the same as strftime
1722 assert dt.strftime() == '{0}'.format(dt)
1723 # check a given format string acts like strftime
1724 assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt)
1725 assert 'the year is 2000' == 'the year is {dt:%Y}'.format(dt=dt)
1726
1727
1728 def test_string_format2():
1729 dt = cftime.datetime(-4713, 1, 1, 12, 0, 0, 10)
1730 # check a given format string acts like strftime
1731 assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt)
1732 assert dt.strftime() == '-4713-01-01 12:00:00'
1733 assert dt.strftime('%Y-%m-%d %H:%M:%S') == '-4713-01-01 12:00:00'
1734 assert dt.strftime('%Y-%m-%d %H:%M:%S.%f') == '-4713-01-01 12:00:00.000010'
1735 assert dt.strftime('%d.%m.%Y %H:%M:%S.%f') == '01.01.-4713 12:00:00.000010'
1736 dt = cftime.datetime(-713, 1, 1, 12, 0, 0, 10)
1737 assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt)
1738 assert dt.strftime() == '-0713-01-01 12:00:00'
1739 assert dt.strftime('%Y-%m-%d %H:%M:%S') == '-0713-01-01 12:00:00'
1740 assert dt.strftime('%Y-%m-%d %H:%M:%S.%f') == '-0713-01-01 12:00:00.000010'
1741 assert dt.strftime('%d.%m.%Y %H:%M:%S.%f') == '01.01.-0713 12:00:00.000010'
1742
1743 def test_strptime():
1744 d = cftime.datetime.strptime('24/Aug/2004:17:57:26 +0200', '%d/%b/%Y:%H:%M:%S %z',calendar='julian',has_year_zero=True)
1745 assert repr(d) == "cftime.datetime(2004, 8, 24, 15, 57, 26, 0, calendar='julian', has_year_zero=True)"
1746 d = cftime.datetime.strptime("0000-02-30",\
1747 "%Y-%m-%d",calendar='360_day',has_year_zero=True)
1748 assert repr(d) == "cftime.datetime(0, 2, 30, 0, 0, 0, 0, calendar='360_day', has_year_zero=True)"
1749 d = cftime.datetime.strptime('-9999-02-29 10:18:32.926',\
1750 '%Y-%m-%d %H:%M:%S.%f',calendar='366_day')
1751 assert repr(d) == "cftime.datetime(-9999, 2, 29, 10, 18, 32, 926000, calendar='all_leap', has_year_zero=True)"
1752 d = cftime.datetime.strptime("20200230", "%Y%m%d", "360_day") # no separator, issue #301
1753 assert repr(d) == "cftime.datetime(2020, 2, 30, 0, 0, 0, 0, calendar='360_day', has_year_zero=True)"
1754 d = cftime.datetime.strptime('24/Aug/-4712:17:57:26', '%d/%b/%Y:%H:%M:%S',calendar='julian')
1755 assert repr(d) == "cftime.datetime(-4712, 8, 24, 17, 57, 26, 0, calendar='julian', has_year_zero=False)"
1756 d = cftime.datetime.strptime('24/August/-4712:17:57:26', '%d/%B/%Y:%H:%M:%S',calendar='julian')
1757 assert repr(d) == "cftime.datetime(-4712, 8, 24, 17, 57, 26, 0, calendar='julian', has_year_zero=False)"
1758 d = cftime.datetime.strptime("-4712", "%Y", calendar="julian")
1759 assert repr(d) == "cftime.datetime(-4712, 1, 1, 0, 0, 0, 0, calendar='julian', has_year_zero=False)"
1760 # should fail with KeyError
1761 try:
1762 d=cftime.datetime.strptime("2000-45-3", "%G-%V-%u", calendar="noleap")
1763 except KeyError:
1764 pass
1765 else:
1766 raise AssertionError
1767
1768
1769 def test_string_isoformat():
1770 dt = cftime.datetime(-4713, 1, 1, 12, 0, 0, 10)
1771 assert dt.isoformat() == '-4713-01-01T12:00:00.000010'
1772 assert dt.isoformat(' ', 'days') == '-4713-01-01'
1773 assert dt.isoformat(' ', 'seconds') == '-4713-01-01 12:00:00'
1774 assert dt.isoformat(' ', 'microseconds') == '-4713-01-01 12:00:00.000010'
1775 dt = cftime.datetime(-713, 1, 1, 12, 0, 0, 10)
1776 assert dt.isoformat() == '-0713-01-01T12:00:00.000010'
1777 assert dt.isoformat(' ', 'days') == '-0713-01-01'
1778 assert dt.isoformat(' ', 'seconds') == '-0713-01-01 12:00:00'
1779 assert dt.isoformat(' ', 'microseconds') == '-0713-01-01 12:00:00.000010'
1780
1781
1782 def test_dayofyr_after_replace(date_type):
1783 date = date_type(1, 1, 1)
1784 assert date.dayofyr == 1
1785 assert date.replace(day=2).dayofyr == 2
1786
1787
1788 def test_dayofwk_after_replace(date_type):
1789 date = date_type(1, 1, 1)
1790 original_dayofwk = date.dayofwk
1791 expected = (original_dayofwk + 1) % 7
1792 result = date.replace(day=2).dayofwk
1793 assert result == expected
1794
1795
1796 def test_daysinmonth_non_leap(date_type, month, days_per_month_non_leap_year):
1797 date = date_type(1, month, 1)
1798 assert date.daysinmonth == days_per_month_non_leap_year
1799
1800
1801 def test_daysinmonth_leap(date_type, month, days_per_month_leap_year):
1802 date = date_type(2000, month, 1)
1803 assert date.daysinmonth == days_per_month_leap_year
1804
1805
1806 @pytest.mark.parametrize('argument', ['dayofyr', 'dayofwk'])
1807 def test_replace_dayofyr_or_dayofwk_error(date_type, argument):
1808 with pytest.raises(ValueError):
1809 date_type(1, 1, 1).replace(**{argument: 3})
1810
1811
1812 def test_dayofyr_after_timedelta_addition(date_type):
1813 initial_date = date_type(1, 1, 2)
1814 date_after_timedelta_addition = initial_date + timedelta(days=1)
1815 assert initial_date.dayofyr == 2
1816 assert date_after_timedelta_addition.dayofyr == 3
1817
1818
1819 def test_exact_datetime_difference(date_type):
1820 b = date_type(2000, 1, 2, 0, 0, 0, 5)
1821 a = date_type(2000, 1, 2)
1822 result = b - a
1823 expected = timedelta(microseconds=5)
1824 assert result == expected
1825
1826
1827 _SHAPES = [(4, ), (2, 2)]
1828 _MICROSECOND_UNITS = ["microseconds", "microsecond", "microsec", "microsecs"]
1829 _MILLISECOND_UNITS = ["milliseconds", "millisecond", "millisec", "millisecs", "ms"]
1830 _SECOND_UNITS = ["seconds", "second", "sec", "secs", "s"]
1831 _MINUTE_UNITS = ["minutes", "minute", "min", "mins"]
1832 _HOUR_UNITS = ["hours", "hour", "hr", "hrs", "h"]
1833 _DAY_UNITS = ["day", "days", "d"]
1834 _MONTH_UNITS = ["month", "months"]
1835 _YEAR_UNITS = ["common_years", "common_year"]
1836 _DTYPES = [np.dtype("int64"), np.dtype("float64")]
1837 _STANDARD_CALENDARS = [
1838 "standard",
1839 "gregorian",
1840 "proleptic_gregorian"
1841 ]
1842 _REAL_WORLD_CALENDARS = [
1843 "julian",
1844 "standard",
1845 "gregorian",
1846 "proleptic_gregorian"
1847 ]
1848 _NO_YEAR_ZERO_CALENDARS = [
1849 "julian",
1850 "standard",
1851 "gregorian",
1852 ]
1853 _ARTIFICIAL_CALENDARS = ["noleap", "all_leap", "360_day"]
1854
1855
1856 @pytest.fixture(params=_SHAPES)
1857 def shape(request):
1858 return request.param
1859
1860
1861 @pytest.fixture(params=_DTYPES)
1862 def dtype(request):
1863 return request.param
1864
1865
1866 @pytest.fixture(params=list(_EXPECTED_DATE_TYPES.keys()))
1867 def calendar(request):
1868 return request.param
1869
1870
1871 @pytest.mark.parametrize("unit", _MICROSECOND_UNITS)
1872 def test_num2date_microsecond_units(calendar, unit, shape, dtype):
1873 date_type = _EXPECTED_DATE_TYPES[calendar]
1874 expected = np.array([date_type(2000, 1, 1, 0, 0, 0, 1),
1875 date_type(2000, 1, 1, 0, 0, 0, 2),
1876 date_type(2000, 1, 1, 0, 0, 0, 3),
1877 date_type(2000, 1, 1, 0, 0, 0, 4)]).reshape(shape)
1878 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1879 units = "{} since 2000-01-01".format(unit)
1880 result = num2date(numeric_times, units=units, calendar=calendar)
1881 np.testing.assert_equal(result, expected)
1882
1883
1884 @pytest.mark.parametrize("unit", _MILLISECOND_UNITS)
1885 def test_num2date_millisecond_units(calendar, unit, shape, dtype):
1886 date_type = _EXPECTED_DATE_TYPES[calendar]
1887 expected = np.array([date_type(2000, 1, 1, 0, 0, 0, 1000),
1888 date_type(2000, 1, 1, 0, 0, 0, 2000),
1889 date_type(2000, 1, 1, 0, 0, 0, 3000),
1890 date_type(2000, 1, 1, 0, 0, 0, 4000)]).reshape(shape)
1891 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1892 units = "{} since 2000-01-01".format(unit)
1893 result = num2date(numeric_times, units=units, calendar=calendar)
1894 np.testing.assert_equal(result, expected)
1895
1896
1897 @pytest.mark.parametrize("unit", _SECOND_UNITS)
1898 def test_num2date_second_units(calendar, unit, shape, dtype):
1899 date_type = _EXPECTED_DATE_TYPES[calendar]
1900 expected = np.array([date_type(2000, 1, 1, 0, 0, 1, 0),
1901 date_type(2000, 1, 1, 0, 0, 2, 0),
1902 date_type(2000, 1, 1, 0, 0, 3, 0),
1903 date_type(2000, 1, 1, 0, 0, 4, 0)]).reshape(shape)
1904 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1905 units = "{} since 2000-01-01".format(unit)
1906 result = num2date(numeric_times, units=units, calendar=calendar)
1907 np.testing.assert_equal(result, expected)
1908
1909
1910 @pytest.mark.parametrize("unit", _MINUTE_UNITS)
1911 def test_num2date_minute_units(calendar, unit, shape, dtype):
1912 date_type = _EXPECTED_DATE_TYPES[calendar]
1913 expected = np.array([date_type(2000, 1, 1, 0, 1, 0, 0),
1914 date_type(2000, 1, 1, 0, 2, 0, 0),
1915 date_type(2000, 1, 1, 0, 3, 0, 0),
1916 date_type(2000, 1, 1, 0, 4, 0, 0)]).reshape(shape)
1917 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1918 units = "{} since 2000-01-01".format(unit)
1919 result = num2date(numeric_times, units=units, calendar=calendar)
1920 np.testing.assert_equal(result, expected)
1921
1922
1923 @pytest.mark.parametrize("unit", _HOUR_UNITS)
1924 def test_num2date_hour_units(calendar, unit, shape, dtype):
1925 date_type = _EXPECTED_DATE_TYPES[calendar]
1926 expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0),
1927 date_type(2000, 1, 1, 2, 0, 0, 0),
1928 date_type(2000, 1, 1, 3, 0, 0, 0),
1929 date_type(2000, 1, 1, 4, 0, 0, 0)]).reshape(shape)
1930 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1931 units = "{} since 2000-01-01".format(unit)
1932 result = num2date(numeric_times, units=units, calendar=calendar)
1933 np.testing.assert_equal(result, expected)
1934
1935
1936 @pytest.mark.parametrize("unit", _DAY_UNITS)
1937 def test_num2date_day_units(calendar, unit, shape, dtype):
1938 date_type = _EXPECTED_DATE_TYPES[calendar]
1939 expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0),
1940 date_type(2000, 1, 3, 0, 0, 0, 0),
1941 date_type(2000, 1, 4, 0, 0, 0, 0),
1942 date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape)
1943 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1944 units = "{} since 2000-01-01".format(unit)
1945 result = num2date(numeric_times, units=units, calendar=calendar)
1946 np.testing.assert_equal(result, expected)
1947
1948
1949 @pytest.mark.parametrize("unit", _MONTH_UNITS)
1950 def test_num2date_month_units(calendar, unit, shape, dtype):
1951 date_type = _EXPECTED_DATE_TYPES[calendar]
1952 expected = np.array([date_type(2000, 2, 1, 0, 0, 0, 0),
1953 date_type(2000, 3, 1, 0, 0, 0, 0),
1954 date_type(2000, 4, 1, 0, 0, 0, 0),
1955 date_type(2000, 5, 1, 0, 0, 0, 0)]).reshape(shape)
1956 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1957 units = "{} since 2000-01-01".format(unit)
1958
1959 if calendar != "360_day":
1960 with pytest.raises(ValueError):
1961 num2date(numeric_times, units=units, calendar=calendar)
1962 else:
1963 result = num2date(numeric_times, units=units, calendar=calendar)
1964 np.testing.assert_equal(result, expected)
1965
1966 @pytest.mark.parametrize("unit", _YEAR_UNITS)
1967 def test_num2date_year_units(calendar, unit, shape, dtype):
1968 date_type = _EXPECTED_DATE_TYPES[calendar]
1969 expected = np.array([date_type(2001, 1, 1, 0, 0, 0, 0),
1970 date_type(2002, 1, 1, 0, 0, 0, 0),
1971 date_type(2003, 1, 1, 0, 0, 0, 0),
1972 date_type(2004, 1, 1, 0, 0, 0, 0)]).reshape(shape)
1973 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1974 units = "{} since 2000-01-01".format(unit)
1975
1976 if calendar not in {"365_day", "noleap"}:
1977 with pytest.raises(ValueError):
1978 num2date(numeric_times, units=units, calendar=calendar)
1979 else:
1980 result = num2date(numeric_times, units=units, calendar=calendar)
1981 np.testing.assert_equal(result, expected)
1982
1983
1984 def test_num2date_only_use_python_datetimes(calendar, shape, dtype):
1985 date_type = real_datetime
1986 expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0),
1987 date_type(2000, 1, 3, 0, 0, 0, 0),
1988 date_type(2000, 1, 4, 0, 0, 0, 0),
1989 date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape)
1990 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
1991 units = "days since 2000-01-01"
1992 if calendar not in _STANDARD_CALENDARS:
1993 with pytest.raises(ValueError):
1994 num2date(numeric_times, units=units, calendar=calendar,
1995 only_use_python_datetimes=True,
1996 only_use_cftime_datetimes=False)
1997 else:
1998 result = num2date(numeric_times, units=units, calendar=calendar,
1999 only_use_python_datetimes=True,
2000 only_use_cftime_datetimes=False)
2001 np.testing.assert_equal(result, expected)
2002
2003
2004 def test_num2date_use_pydatetime_if_possible(calendar, shape, dtype):
2005 if calendar not in _STANDARD_CALENDARS:
2006 date_type = _EXPECTED_DATE_TYPES[calendar]
2007 else:
2008 date_type = real_datetime
2009
2010 expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0),
2011 date_type(2000, 1, 3, 0, 0, 0, 0),
2012 date_type(2000, 1, 4, 0, 0, 0, 0),
2013 date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape)
2014 numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype)
2015 units = "days since 2000-01-01"
2016 result = num2date(numeric_times, units=units, calendar=calendar,
2017 only_use_python_datetimes=False,
2018 only_use_cftime_datetimes=False)
2019 np.testing.assert_equal(result, expected)
2020
2021
2022 @pytest.mark.parametrize(
2023 ["standard_calendar", "breakpoint"],
2024 [("proleptic_gregorian", "{}-12-31T23:59:59.999999".format(MINYEAR - 1)),
2025 ("gregorian", "1582-10-15"),
2026 ("standard", "1582-10-15")]
2027 )
2028 def test_num2date_only_use_python_datetimes_invalid_basedate(
2029 standard_calendar,
2030 breakpoint
2031 ):
2032 units = "days since {}".format(breakpoint)
2033 numeric_times = np.array([1, 2, 3, 4])
2034 with pytest.raises(ValueError):
2035 num2date(
2036 numeric_times,
2037 units=units,
2038 calendar=standard_calendar,
2039 only_use_python_datetimes=True,
2040 only_use_cftime_datetimes=False
2041 )
2042
2043
2044 @pytest.mark.parametrize("real_world_calendar", _NO_YEAR_ZERO_CALENDARS)
2045 def test_num2date_invalid_zero_reference_year(real_world_calendar):
2046 units = "days since 0000-01-01"
2047 numeric_times = np.array([1, 2, 3, 4])
2048 with pytest.raises(ValueError, match="zero not allowed as a reference"):
2049 num2date(
2050 numeric_times,
2051 units=units,
2052 calendar=real_world_calendar
2053 )
2054
2055
2056 @pytest.mark.parametrize("artificial_calendar", _ARTIFICIAL_CALENDARS)
2057 def test_num2date_valid_zero_reference_year(artificial_calendar):
2058 units = "days since 0000-01-01"
2059 numeric_times = np.array([1, 2, 3, 4])
2060 num2date(numeric_times, units=units, calendar=artificial_calendar)
2061
2062
2063 def test_num2date_masked_array(calendar):
2064 date_type = _EXPECTED_DATE_TYPES[calendar]
2065 expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0),
2066 date_type(2000, 1, 1, 2, 0, 0, 0),
2067 date_type(2000, 1, 1, 3, 0, 0, 0),
2068 date_type(2000, 1, 1, 4, 0, 0, 0)])
2069 mask = [False, False, True, False]
2070 expected = np.ma.masked_array(expected, mask=mask)
2071 numeric_times = np.ma.masked_array([1, 2, 3, 4], mask=mask)
2072 units = "hours since 2000-01-01"
2073 result = num2date(numeric_times, units=units, calendar=calendar)
2074 np.testing.assert_equal(result, expected)
2075
2076
2077 def test_num2date_out_of_range():
2078 numeric_times = 12 * np.array([200000, 400000, 600000])
2079 units = "months since 2000-01-01"
2080 with pytest.raises(OverflowError, match="time values outside range of 64 bit signed integers"):
2081 num2date(numeric_times, units=units, calendar="360_day")
2082
2083
2084 def test_num2date_list_input(calendar):
2085 date_type = _EXPECTED_DATE_TYPES[calendar]
2086 expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0),
2087 date_type(2000, 1, 1, 2, 0, 0, 0),
2088 date_type(2000, 1, 1, 3, 0, 0, 0),
2089 date_type(2000, 1, 1, 4, 0, 0, 0)])
2090 numeric_times = [1, 2, 3, 4]
2091 units = "hours since 2000-01-01"
2092 result = num2date(numeric_times, units=units, calendar=calendar)
2093 np.testing.assert_equal(result, expected)
2094
2095
2096 def test_num2date_integer_upcast_required():
2097 numeric_times = np.array([30, 60, 90, 120], dtype=np.int32)
2098 units = "minutes since 2000-01-01"
2099 expected = np.array([
2100 Datetime360Day(2000, 1, 1, 0, 30, 0),
2101 Datetime360Day(2000, 1, 1, 1, 0, 0),
2102 Datetime360Day(2000, 1, 1, 1, 30, 0),
2103 Datetime360Day(2000, 1, 1, 2, 0, 0)
2104 ])
2105 result = num2date(numeric_times, units=units, calendar="360_day")
2106 np.testing.assert_equal(result, expected)
2107
2108
2109 @pytest.mark.parametrize(
2110 "encoding_units",
2111 ["microseconds", "milliseconds", "seconds", "minutes", "hours", "days"]
2112 )
2113 @pytest.mark.parametrize(
2114 "freq",
2115 [
2116 timedelta(microseconds=1),
2117 timedelta(microseconds=1000),
2118 timedelta(seconds=1),
2119 timedelta(minutes=1),
2120 timedelta(hours=1),
2121 timedelta(days=1)
2122 ],
2123 ids=lambda x: f"{x!r}"
2124 )
2125 def test_date2num_num2date_roundtrip(encoding_units, freq, calendar):
2126 date_type = _EXPECTED_DATE_TYPES[calendar]
2127 lengthy_timedelta = timedelta(days=291000 * 360)
2128 times = np.array(
2129 [
2130 date_type(1, 1, 1),
2131 date_type(1, 1, 1) + lengthy_timedelta,
2132 date_type(1, 1, 1) + lengthy_timedelta + freq
2133 ]
2134 )
2135 units = f"{encoding_units} since 0001-01-01"
2136 encoded = date2num(times, units=units, calendar=calendar)
2137 decoded = num2date(encoded, units=units, calendar=calendar)
2138 encoding_units_as_timedelta = timedelta(microseconds=UNIT_CONVERSION_FACTORS[encoding_units])
2139
2140 if freq >= encoding_units_as_timedelta:
2141 assert encoded.dtype == np.int64
2142 np.testing.assert_equal(decoded, times)
2143 else:
2144 # if sys.platform.startswith("win"):
2145 # assert encoded.dtype == np.float64
2146 # else:
2147 # assert encoded.dtype == np.float128
2148 assert encoded.dtype == np.float64
2149 tolerance = timedelta(microseconds=2000)
2150 meets_tolerance = np.abs(decoded - times) <= tolerance
2151 assert np.all(meets_tolerance)
2152
2153
2154 def test_date2num_missing_data():
2155 # Masked array
2156 a = [
2157 cftime.DatetimeGregorian(2000, 12, 1),
2158 cftime.DatetimeGregorian(2000, 12, 2),
2159 cftime.DatetimeGregorian(2000, 12, 3),
2160 cftime.DatetimeGregorian(2000, 12, 4),
2161 ]
2162 mask = [True, False, True, False]
2163 array = np.ma.array(a, mask=mask)
2164 out = date2num(array, units="days since 2000-12-01", calendar="standard")
2165 assert ((out == np.ma.array([-99, 1, -99, 3], mask=mask)).all())
2166 assert ((out.mask == mask).all())
2167
2168 # Scalar masked array
2169 a = cftime.DatetimeGregorian(2000, 12, 1)
2170 mask = True
2171 array = np.ma.array(a, mask=mask)
2172 out = date2num(array, units="days since 2000-12-01", calendar="standard")
2173 assert out is np.ma.masked
2174
2175
2176 def test_date2num_numpy_datetime64():
2177 # Array
2178 array = np.array([
2179 np.datetime64(123, "s"),
2180 np.datetime64(124, "s"),
2181 np.datetime64(125, "s")
2182 ])
2183 out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian")
2184 assert ((out == np.array([123, 124, 125]))).all()
2185
2186 # Scalar
2187 array = np.datetime64(123, "s")
2188 out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian")
2189 assert out == np.int64(123)
2190
2191
2192 def test_num2date_preserves_shape():
2193 # The optimized num2date algorithm operates on a flattened array. This
2194 # check ensures that the original shape of the times is restored in the
2195 # result.
2196 a = np.array([[0, 1, 2], [3, 4, 5]])
2197 result = num2date(a, units="days since 2000-01-01", calendar="standard")
2198 expected = np.array([cftime.DatetimeGregorian(2000, 1, i) for i in range(1, 7)]).reshape((2, 3))
2199 np.testing.assert_equal(result, expected)
2200
2201
2202 def test_num2date_preserves_order():
2203 # The optimized num2date algorithm sorts the encoded times before decoding them.
2204 # This check ensures that the order of the times is restored in the result.
2205 a = np.array([1, 0])
2206 result = num2date(a, units="days since 2000-01-01", calendar="standard")
2207 expected = np.array([cftime.DatetimeGregorian(2000, 1, i) for i in [2, 1]])
2208 np.testing.assert_equal(result, expected)
2209
2210
2211 def test_num2date_empty_array():
2212 a = np.array([[]])
2213 result = num2date(a, units="days since 2000-01-01", calendar="standard")
2214 expected = np.array([[]], dtype="O")
2215 np.testing.assert_equal(result, expected)
2216
2217
2218 DATEPARSE_ERROR_TESTS = [
2219 ("foo", "In general, units must be"),
2220 ("months", "'months since' units only allowed"),
2221 ("common_years", "'common_years' units only allowed")
2222 ]
2223
2224
2225 @pytest.mark.parametrize(("units", "match"), DATEPARSE_ERROR_TESTS)
2226 def test_num2date_unrecognized_units(units, match):
2227 with pytest.raises(ValueError, match=match):
2228 num2date(0.0, units=f"{units} since 2000-01-01", calendar="standard")
2229
2230
2231 @pytest.mark.parametrize(("units", "match"), DATEPARSE_ERROR_TESTS)
2232 def test_date2num_unrecognized_units(units, match):
2233 date = cftime.datetime(2000, 1, 1, calendar="standard")
2234 with pytest.raises(ValueError, match=match):
2235 date2num(date, units=f"{units} since 2000-01-01", calendar="standard")
2236
2237
2238 def test_num2date_precision():
2239 if np.finfo(np.longdouble).precision < 18:
2240 pytest.skip("skipping tests that require extended precision longdouble type")
2241 testdates = [(1271, 3, 18, 19, 41, 33),
2242 (1271, 3, 18, 19, 41, 32, 999998)]
2243 unitinc = ['microseconds', 'seconds', 'minutes', 'hours', 'days']
2244 for cc in ['standard', 'gregorian', 'julian', 'proleptic_gregorian',
2245 'noleap', 'all_leap', '365_day', '366_day', '360_day']:
2246 for uinc in unitinc:
2247 if cc in ['standard', 'gregorian', 'julian']:
2248 units = uinc + ' since -4713-01-01 12:00:00'
2249 elif cc in ['proleptic_gregorian']:
2250 units = uinc + ' since -4714-01-01 12:00:00'
2251 elif cc in ['noleap', 'all_leap', '365_day', '366_day', '360_day']:
2252 units = uinc + ' since 0000-01-01 12:00:00'
2253 # scalar
2254 date = datetimex(*testdates[0], calendar=cc)
2255 num = date2num(date, units, calendar=cc, longdouble=True)
2256 date2 = num2date(num, units, calendar=cc)
2257 assert date == date2
2258 # array
2259 date = [ datetimex(*dd, calendar=cc) for dd in testdates ]
2260 num = date2num(date, units, calendar=cc, longdouble=True)
2261 date2 = num2date(num, units, calendar=cc)
2262 for i in range(len(date)):
2263 assert date[i] == date2[i]
2264 # masked array
2265 num = np.ma.array(num, mask=(True, False))
2266 date2 = num2date(num, units, calendar=cc)
2267 assert np.ma.is_masked(date2[0])
2268 assert date[1] == date2[1]
2269
2270 # NOTE: using pytest style tests -- these won't run without pytest
2271 # but it looks like you're using pytest, so this is cleaner and easier
2272
2273 # There's really no reason to put these in a class, but it does organize things
2274 class Test_tai:
2275 """
2276 tests specific to the tai calendar
2277 """
2278 def test_dateparse_valid(self):
2279 """
2280 It should raise for an epoch before 1958
2281 """
2282 # This is directly testing the _dateparse function
2283 # Which is a "proper" unit test, but also testing an internal function.
2284 timestring = "seconds since 1958-01-01T00:00:00"
2285 basedate = cftime._dateparse(timestring, 'tai')
2286
2287 print(repr(basedate))
2288
2289 assert basedate == cftime.datetime(1958, 1, 1, 0, 0, 0, 0, calendar='tai', has_year_zero=False)
2290
2291 def test_dateparse_before_1958(self):
2292 """
2293 It should raise for an epoch before 1958
2294 """
2295 # This is directly testing the _dateparse function
2296 # Which is a "proper" unit test, but also testing an internal function.
2297 timestring = "seconds since 1957-01-01T00:00:00"
2298 with pytest.raises(ValueError):
2299 basedate = cftime._dateparse(timestring, 'tai')
2300 # cftime._dateparse(timestring, 'tai', has_year_zero=None)
2301 print(basedate)
2302
2303 def test_dateparse_with_offset(self):
2304 """
2305 It should raise if there's an offset
2306 """
2307 # This is directly testing the _dateparse function
2308 # Which is a "proper" unit test, but also testing an internal function.
2309 timestring = "seconds since 1965-01-01T00:00:00+08:00"
2310 with pytest.raises(ValueError):
2311 basedate = cftime._dateparse(timestring, 'tai')
2312 # cftime._dateparse(timestring, 'tai', has_year_zero=None)
2313 print(basedate)
2314
2315 def test_year_zero(self):
2316 """
2317 tai does not have a year zero -- not sure this is worth testing, but for full coverage.
2318 """
2319 # This is directly testing the _dateparse function
2320 # Which is a "proper" unit test, but also testing an internal function.
2321 timestring = "seconds since 1965-01-01T00:00:00"
2322 with pytest.raises(ValueError):
2323 basedate = cftime._dateparse(timestring, 'tai', has_year_zero=True)
2324 # cftime._dateparse(timestring, 'tai', has_year_zero=None)
2325 print(basedate)
2326
2327 def test_creation_valid(self):
2328 dt = DatetimeTAI(2025, 1, 9, 14, 18)
2329
2330 assert dt.calendar == 'tai'
2331 assert dt.has_year_zero is False
2332
2333 print(repr(dt))
2334
2335 def test_creation_before_1958(self):
2336 with pytest.raises(ValueError):
2337 dt = DatetimeTAI(1957, 1, 9, 14, 18)
2338 print(repr(dt))
2339
2340
2341
2342 if __name__ == '__main__':
2343 unittest.main()