import cftime from cftime import datetime as datetimex from cftime import real_datetime from cftime import (Datetime360Day, DatetimeAllLeap, DatetimeGregorian, DatetimeJulian, DatetimeNoLeap, DatetimeProlepticGregorian, DatetimeTAI, _parse_date, date2index, date2num, num2date, UNIT_CONVERSION_FACTORS) import copy import unittest import warnings from collections import namedtuple from datetime import datetime, timedelta, MINYEAR import numpy as np import pytest from numpy.testing import assert_almost_equal, assert_equal try: from datetime import timezone except ImportError: # python2.7 from datetime import tzinfo class timezone(tzinfo): """ Fixed offset in minutes east from UTC. adapted from python 2.7 docs FixedOffset """ def __init__(self, offset, name): self.__offset = offset self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return timedelta(hours=0) # legacy class included here since tests use it. class utime: def __init__(self, unit_string, calendar='standard', only_use_cftime_datetimes=True, only_use_python_datetimes=False): calendar = calendar.lower() units, isostring = cftime._datesplit(unit_string) self.origin = cftime._dateparse(unit_string,calendar=calendar) self.units = units self.calendar = calendar self.unit_string = unit_string self.only_use_cftime_datetimes = only_use_cftime_datetimes self.only_use_python_datetimes = only_use_python_datetimes def date2num(self, date): return date2num(date,self.unit_string,calendar=self.calendar) def num2date(self, time_value): 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) utc = timezone(timedelta(hours=0), 'UTC') est = timezone(timedelta(hours=-5), 'UTC') # test cftime module for netCDF time <--> python datetime conversions. dtime = namedtuple('dtime', ('values', 'units', 'calendar')) dateformat = '%Y-%m-%d %H:%M:%S' dateformat2 = '%y-%m-%d %H:%M:%S' calendars=['standard', 'gregorian', 'proleptic_gregorian', 'noleap', 'julian',\ 'all_leap', '365_day', '366_day', '360_day'] def adjust_calendar(calendar): # check for and remove calendar synonyms. calendar = calendar.lower() if calendar == 'gregorian' or calendar == 'standard': return 'standard' elif calendar == 'noleap' or calendar == '365_day': return 'noleap' elif calendar == 'all_leap' or calendar == '366_day': return 'all_leap' else: return calendar class CFTimeVariable(object): '''dummy "netCDF" variable to hold time info''' def __init__(self, values, calendar='standard', units=None): self.values = np.asarray(values) self.calendar = calendar self.units = units def __array__(self): # np special method that returns a np array. return self.values[...] def __getitem__(self, indexers): return self.values[indexers] def __repr__(self): print('units: ', self.units) print('calendar: ', self.calendar) print('') return repr(self.values) def __str__(self): return self.__repr__() def __len__(self): return len(self.values) @property def shape(self): return self.values.shape class cftimeTestCase(unittest.TestCase): def setUp(self): self.cdftime_mixed = utime('hours since 0001-01-01 00:00:00') self.cdftime_julian = utime( 'hours since 0001-01-01 00:00:00', calendar='julian') self.cdftime_mixed_tz = utime('hours since 0001-01-01 00:00:00 -06:00') self.cdftime_pg = utime('seconds since 0001-01-01 00:00:00', calendar='proleptic_gregorian') self.cdftime_noleap = utime( 'days since 1600-02-28 00:00:00', calendar='noleap') self.cdftime_leap = utime( 'days since 1600-02-29 00:00:00', calendar='all_leap') self.cdftime_360day = utime( 'days since 1600-02-30 00:00:00', calendar='360_day') self.cdftime_jul = utime( 'hours since 1000-01-01 00:00:00', calendar='julian') self.cdftime_iso = utime("seconds since 1970-01-01T00:00:00Z") self.cdftime_leading_space = utime("days since 850-01-01 00:00:00") self.cdftime_mixed_capcal = utime('hours since 0001-01-01 00:00:00', calendar='Standard') self.cdftime_noleap_capcal = utime( 'days since 1600-02-28 00:00:00', calendar='NOLEAP') def test_tz_aware(self): """testing with timezone""" self.assertTrue(self.cdftime_mixed.units == 'hours') d1 = datetime(1582, 10, 4, 23, tzinfo=utc) t1 = self.cdftime_mixed.date2num(d1) d2 = datetime(1582, 10, 4, 18, tzinfo=est) t2 = self.cdftime_mixed.date2num(d2) assert_almost_equal(t1, 13865687.0) assert_almost_equal(t2, 13865682.0) # est is 5 hours behind utc def test_tz_naive(self): """testing cftime""" # test mixed julian/gregorian calendar # check attributes. self.assertTrue(self.cdftime_mixed.units == 'hours') self.assertTrue( str(self.cdftime_mixed.origin) == '0001-01-01 00:00:00') self.assertTrue( self.cdftime_mixed.unit_string == 'hours since 0001-01-01 00:00:00') self.assertTrue(self.cdftime_mixed.calendar == 'standard') # check date2num method. (date before switch) d = datetime(1582, 10, 4, 23) t1 = self.cdftime_mixed.date2num(d) assert_almost_equal(t1, 13865687.0) # check num2date method. d2 = self.cdftime_mixed.num2date(t1) self.assertTrue(str(d) == str(d2)) # this is a non-existent date, should raise ValueError. d = datetime(1582, 10, 5, 0) self.assertRaises(ValueError, self.cdftime_mixed.date2num, d) # check date2num/num2date with date after switch. d = datetime(1582, 10, 15, 0) t2 = self.cdftime_mixed.date2num(d) assert_almost_equal(t2, 13865688.0) d2 = self.cdftime_mixed.num2date(t2) self.assertTrue(str(d) == str(d2)) # check day of year. ndayr = d.timetuple()[7] self.assertTrue(ndayr == 288) # test using np arrays. t = np.arange(t2, t2 + 240.0, 12.) t = np.reshape(t, (4, 5)) d = self.cdftime_mixed.num2date(t) self.assertTrue(d.shape == t.shape) 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" d2 = [str(dd) for dd in d.flat] self.assertTrue(d_check == ''.join(d2)) # test julian calendar with np arrays d = self.cdftime_julian.num2date(t) self.assertTrue(d.shape == t.shape) 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" d2 = [str(dd) for dd in d.flat] self.assertTrue(d_check == ''.join(d2)) # test proleptic gregorian calendar. self.assertTrue(self.cdftime_pg.units == 'seconds') self.assertTrue(str(self.cdftime_pg.origin) == '0001-01-01 00:00:00') self.assertTrue( self.cdftime_pg.unit_string == 'seconds since 0001-01-01 00:00:00') self.assertTrue(self.cdftime_pg.calendar == 'proleptic_gregorian') # check date2num method. d = datetime(1990, 5, 5, 2, 17) t1 = self.cdftime_pg.date2num(d) self.assertTrue(np.around(t1) == 62777470620.0) # check num2date method. d2 = self.cdftime_pg.num2date(t1) self.assertTrue(d.strftime(dateformat) == d2.strftime(dateformat)) # make sure two digit years work in strftime (issue #362) self.assertTrue(d.strftime(dateformat2) == d2.strftime(dateformat2)) # issue #401 (check for %y not y) t = cftime.DatetimeGregorian(2026,4,14,0) self.assertTrue(t.strftime('year=%Y') == 'year=2026') # check day of year. ndayr = d.timetuple()[7] self.assertTrue(ndayr == 125) # check noleap calendar. # this is a non-existent date, should raise ValueError. self.assertRaises( ValueError, utime, 'days since 1600-02-29 00:00:00', calendar='noleap') self.assertTrue(self.cdftime_noleap.units == 'days') self.assertTrue( str(self.cdftime_noleap.origin) == '1600-02-28 00:00:00') self.assertTrue( self.cdftime_noleap.unit_string == 'days since 1600-02-28 00:00:00') self.assertTrue(self.cdftime_noleap.calendar == 'noleap') assert_almost_equal( self.cdftime_noleap.date2num(self.cdftime_noleap.origin), 0.0) # check date2num method. d1 = datetime(2000, 2, 28) d2 = datetime(1600, 2, 28) t1 = self.cdftime_noleap.date2num(d1) t2 = self.cdftime_noleap.date2num(d2) assert_almost_equal(t1, 400 * 365.) assert_almost_equal(t2, 0.) t12 = self.cdftime_noleap.date2num([d1, d2]) assert_almost_equal(t12, [400 * 365., 0]) # check num2date method. d2 = self.cdftime_noleap.num2date(t1) self.assertTrue(str(d1) == str(d2)) # check day of year. ndayr = d2.timetuple()[7] self.assertTrue(ndayr == 59) # non-existent date, should raise ValueError. date = datetime(2000, 2, 29) self.assertRaises(ValueError, self.cdftime_noleap.date2num, date) # check all_leap calendar. self.assertTrue(self.cdftime_leap.units == 'days') self.assertTrue( str(self.cdftime_leap.origin) == '1600-02-29 00:00:00') self.assertTrue( self.cdftime_leap.unit_string == 'days since 1600-02-29 00:00:00') self.assertTrue(self.cdftime_leap.calendar == 'all_leap') assert_almost_equal( self.cdftime_leap.date2num(self.cdftime_leap.origin), 0.0) # check date2num method. d1 = datetime(2000, 2, 29) d2 = datetime(1600, 2, 29) t1 = self.cdftime_leap.date2num(d1) t2 = self.cdftime_leap.date2num(d2) assert_almost_equal(t1, 400 * 366.) assert_almost_equal(t2, 0.) # check num2date method. d2 = self.cdftime_leap.num2date(t1) self.assertTrue(str(d1) == str(d2)) # check day of year. ndayr = d2.timetuple()[7] self.assertTrue(ndayr == 60) # double check date2num,num2date methods. d = datetime(2000, 12, 31) t1 = self.cdftime_mixed.date2num(d) d2 = self.cdftime_mixed.num2date(t1) self.assertTrue(str(d) == str(d2)) ndayr = d2.timetuple()[7] self.assertTrue(ndayr == 366) # check 360_day calendar. self.assertTrue(self.cdftime_360day.units == 'days') self.assertTrue( str(self.cdftime_360day.origin) == '1600-02-30 00:00:00') self.assertTrue( self.cdftime_360day.unit_string == 'days since 1600-02-30 00:00:00') self.assertTrue(self.cdftime_360day.calendar == '360_day') assert_almost_equal( self.cdftime_360day.date2num(self.cdftime_360day.origin), 0.0) # check date2num,num2date methods. # use datetime from cftime, since this date doesn't # exist in "normal" calendars. d = datetimex(2000, 2, 30, calendar='') t1 = self.cdftime_360day.date2num(d) assert_almost_equal(t1, 360 * 400.) d2 = self.cdftime_360day.num2date(t1) assert_equal(str(d), str(d2)) # check day of year. d = datetime(2001, 12, 30) t = self.cdftime_360day.date2num(d) assert_almost_equal(t, 144660.0) date = self.cdftime_360day.num2date(t) self.assertTrue(str(d) == str(date)) ndayr = date.timetuple()[7] self.assertTrue(ndayr == 360) # Check fraction d = datetime(1969, 12, 30, 12) t = self.cdftime_360day.date2num(d) date = self.cdftime_360day.num2date(t) assert_equal(str(d), str(date)) # test proleptic julian calendar. d = datetime(1858, 11, 17, 12) t = self.cdftime_jul.date2num(d) assert_almost_equal(t, 7528932.0) d1 = datetime(1582, 10, 4, 23) d2 = datetime(1582, 10, 15, 0) assert_almost_equal( self.cdftime_jul.date2num(d1) + 241.0, self.cdftime_jul.date2num(d2)) date = self.cdftime_jul.num2date(t) self.assertTrue(str(d) == str(date)) # test julian day from date, date from julian day d = cftime.datetime(1858, 11, 17, calendar='standard') # astronomical year numbering (with year zero) dz = cftime.datetime(1858, 11, 17, calendar='standard',has_year_zero=True) # toordinal (with fractional = True) is same as old JulianDayFromDate mjd1 = d.toordinal(fractional=True) mjd1z = dz.toordinal(fractional=True) assert_almost_equal(mjd1, 2400000.5) assert_almost_equal(mjd1z, 2400000.5) # fromordinal (same as old DateFromJulianDay) date1 = cftime.datetime.fromordinal(mjd1) self.assertTrue(str(date1) == str(d)) # test iso 8601 units string d = datetime(1970, 1, 1, 1) t = self.cdftime_iso.date2num(d) assert_equal(np.around(t), 3600) # test fix for issue 75 (seconds hit 60 at end of month, # day goes out of range). t = 733499.0 d = num2date(t, units='days since 0001-01-01 00:00:00') assert_equal(d.strftime(dateformat), '2009-04-01 00:00:00') # test edge case of issue 75 for numerical problems for t in (733498.999, 733498.9999, 733498.99999, 733498.999999, 733498.9999999): d = num2date(t, units='days since 0001-01-01 00:00:00') t2 = date2num(d, units='days since 0001-01-01 00:00:00') assert abs(t2 - t) < 1e-5 # values should be less than second # Check equality testing d1 = datetimex(1979, 6, 21, 9, 23, 12, calendar='standard') d2 = datetime(1979, 6, 21, 9, 23, 12) assert d1 == d2 # check timezone offset d = datetime(2012, 2, 29, 15) # mixed_tz is -6 hours from UTC, mixed is UTC so # difference in elapsed time is -6 hours. assert self.cdftime_mixed_tz.date2num( d) - self.cdftime_mixed.date2num(d) == -6 # Check comparisons with Python datetime types # Note that d1 has to use the proleptic Gregorian calendar to # be comparable to d2: datetime.datetime uses the proleptic # Gregorian calendar and year 1000 is before the # Julian/Gregorian transition (1582-10-15). d1 = num2date(0, 'days since 1000-01-01', 'proleptic_gregorian') d2 = datetime(2000, 1, 1) # The date d3 is well after the Julian/Gregorian transition # and so this Gregorian date can be compared to the proleptic # Gregorian date d2. d3 = num2date(0, 'days since 3000-01-01', 'standard') assert d1 < d2 assert d2 < d3 # check all comparisons assert d1 != d2 assert d1 <= d2 assert d2 > d1 assert d2 >= d1 # check datetime hash d1 = datetimex(1995, 1, 1) d2 = datetime(1995, 1, 1) d3 = datetimex(2001, 2, 20) assert hash(d1) == hash(d1) assert hash(d1) == hash(d2) assert hash(d1) != hash(d3) assert hash(d3) == hash(d3) # check datetime immutability # using assertRaises as a context manager # only works with python >= 2.7 (issue #497). immutability_tests = {"year": 1999, "month": 6, "day": 5, "hour": 10, "minute": 33, "second": 45, "dayofwk": 1, "dayofyr": 52, "format": '%Y'} for name, value in immutability_tests.items(): self.assertRaises(AttributeError, setattr, d1, name, value) # Check leading white space self.assertEqual( str(self.cdftime_leading_space.origin), '0850-01-01 00:00:00') #issue 330 units = "seconds since 1970-01-01T00:00:00Z" t = utime(units) for n in range(10): assert n == int(round(t.date2num(t.num2date(n)))) #issue 344 units = 'hours since 2013-12-12T12:00:00' assert 1.0 == date2num(num2date(1.0, units), units) # test roundtrip accuracy # also tests error found in issue #349 dateref = datetime(2015,2,28,12) verbose = True # print out max error diagnostics ntimes = 101 def roundtrip(delta,eps,units): times1 = date2num(dateref,units,calendar=calendar) times1 += delta*np.arange(0,ntimes) dates1 = num2date(times1,units,calendar=calendar) times2 = date2num(dates1,units,calendar=calendar) dates2 = num2date(times2,units,calendar=calendar) err = np.abs(times1 - times2) assert np.all(err date2num) using 360_day and 365_day calendars." for datetime_class in [Datetime360Day, DatetimeNoLeap]: # Pick a date and time outside of the range of the Julian calendar. date = datetime_class(-5000, 1, 1, 12) converter = self.converters[date.calendar] self.assertEqual(date, converter.num2date(converter.date2num(date))) def test_dayofwk(self): "Test computation of dayofwk in the 365_day calendar." converter = self.converters["noleap"] # Pick the date corresponding to the Julian day of 1.0 to test # the transition from positive to negative Julian days. with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) julian_day = converter.date2num(datetimex(-4712, 1, 2, 12)) # should be a Tuesday old_date = converter.num2date(julian_day) for delta_year in range(1, 101): # 100 years cover several 7-year cycles date = converter.num2date(julian_day - delta_year * 365) # test that the day of the week changes by one every year (except # for wrapping around every 7 years, of course) if date.dayofwk == 6: self.assertEqual(old_date.dayofwk, 0) else: self.assertEqual(old_date.dayofwk - date.dayofwk, 1) old_date = date class DateTime(unittest.TestCase): def setUp(self): self.date1_365_day = DatetimeNoLeap(-5000, 1, 2, 12) self.date2_365_day = DatetimeNoLeap(-5000, 1, 3, 12) self.date3_gregorian = DatetimeGregorian(1969, 7, 20, 12) self.date3_gregorian_yearzero = DatetimeGregorian(1969, 7, 20, 12, has_year_zero=True) with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) self.date4_proleptic_gregorian = cftime.datetime(-1,5,5,2,30,59,999999,calendar='proleptic_gregorian',has_year_zero=False) self.date4_julian = self.date4_proleptic_gregorian.change_calendar('julian',True) # last day of the Julian calendar in the mixed Julian/Gregorian calendar self.date4_gregorian = DatetimeGregorian(1582, 10, 4) # first day of the Gregorian calendar in the mixed Julian/Gregorian calendar self.date5_gregorian = DatetimeGregorian(1582, 10, 15) self.date6_proleptic_gregorian = DatetimeProlepticGregorian(1582, 10, 15) self.date7_360_day = Datetime360Day(2000, 1, 1) self.date8_julian = DatetimeJulian(1582, 10, 4) # a datetime.datetime instance (proleptic Gregorian calendar) self.datetime_date1 = datetime(1969, 7, 21, 12) self.delta = timedelta(hours=25) def test_add(self): dt = self.date1_365_day # datetime + timedelta self.assertEqual(dt + self.delta, # add 25 hours dt.replace(day=dt.day + 1, hour=dt.hour + 1)) # timedelta + datetime self.assertEqual(self.delta + dt, # add 25 hours dt.replace(day=dt.day + 1, hour=dt.hour + 1)) # test the Julian/Gregorian transition self.assertEqual(self.date4_gregorian + self.delta, DatetimeGregorian(1582, 10, 15, 1)) # The Julian calendar has no invalid dates self.assertEqual(self.date8_julian + self.delta, DatetimeJulian(1582, 10, 5, 1)) # Test going over the year boundary. self.assertEqual(DatetimeGregorian(2000, 11, 1) + timedelta(days=30 + 31), DatetimeGregorian(2001, 1, 1)) # Year 2000 is a leap year. self.assertEqual(DatetimeGregorian(2000, 1, 1) + timedelta(days=31 + 29), DatetimeGregorian(2000, 3, 1)) # Test the 366_day calendar. self.assertEqual(DatetimeAllLeap(1, 1, 1) + timedelta(days=366 * 10 + 31), DatetimeAllLeap(11, 2, 1)) # The Gregorian calendar has no year zero. with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) self.assertEqual(DatetimeGregorian(-1, 12, 31) + self.delta, DatetimeGregorian(1, 1, 1, 1)) def invalid_add_1(): self.date1_365_day + 1 def invalid_add_2(): 1 + self.date1_365_day for func in [invalid_add_1, invalid_add_2]: self.assertRaises(TypeError, func) def test_sub(self): # subtracting a timedelta previous_day = self.date1_365_day - self.delta self.assertEqual(previous_day.day, self.date1_365_day.day - 1) def total_seconds(td): """Equivalent to td.total_seconds() on Python >= 2.7. See https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds """ return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 # sutracting two cftime.datetime instances delta = self.date2_365_day - self.date1_365_day # date1 and date2 are exactly one day apart self.assertEqual(total_seconds(delta), 86400) # subtracting cftime.datetime from datetime.datetime delta = self.datetime_date1 - self.date3_gregorian # real_date2 and real_date1 are exactly one day apart self.assertEqual(total_seconds(delta), 86400) # subtracting datetime.datetime from cftime.datetime delta = self.date3_gregorian - self.datetime_date1 # real_date2 and real_date1 are exactly one day apart self.assertEqual(total_seconds(delta), -86400) # Test the Julian/Gregorian transition. self.assertEqual(self.date5_gregorian - self.delta, DatetimeGregorian(1582, 10, 3, 23)) # The proleptic Gregorian calendar does not have invalid dates. self.assertEqual(self.date6_proleptic_gregorian - self.delta, DatetimeProlepticGregorian(1582, 10, 13, 23)) with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) # The Gregorian calendar has no year zero. self.assertEqual(DatetimeGregorian(1, 1, 1) - self.delta, DatetimeGregorian(-1, 12, 30, 23)) # The 360_day calendar has year zero. self.assertEqual(self.date7_360_day - timedelta(days=2000 * 360), Datetime360Day(0, 1, 1)) # Test going over the year boundary. self.assertEqual(DatetimeGregorian(2000, 3, 1) - timedelta(days=29 + 31 + 31), DatetimeGregorian(1999, 12, 1)) # Year 2000 is a leap year. self.assertEqual(DatetimeGregorian(2000, 3, 1) - self.delta, DatetimeGregorian(2000, 2, 28, 23)) def invalid_sub_1(): self.date1_365_day - 1 def invalid_sub_2(): 1 - self.date1_365_day def invalid_sub_3(): self.date1_365_day - self.datetime_date1 def invalid_sub_4(): self.datetime_date1 - self.date1_365_day def invalid_sub_5(): self.date3_gregorian - self.date1_365_day def invalid_sub_6(): self.date3_gregorian - self.date3_gregorian_yearzero for func in [invalid_sub_1, invalid_sub_2, invalid_sub_3, invalid_sub_4, invalid_sub_5, invalid_sub_6]: self.assertRaises(TypeError, func) def test_replace(self): self.assertEqual(self.date1_365_day.replace(year=4000).year, 4000) self.assertEqual(self.date1_365_day.replace(month=3).month, 3) self.assertEqual(self.date1_365_day.replace(day=3).day, 3) self.assertEqual(self.date1_365_day.replace(hour=3).hour, 3) self.assertEqual(self.date1_365_day.replace(minute=3).minute, 3) self.assertEqual(self.date1_365_day.replace(second=3).second, 3) self.assertEqual(self.date1_365_day.replace(microsecond=3).microsecond, 3) d = datetimex(2000, 2, 3, calendar='noleap') self.assertEqual(d.replace(year=1999).calendar, 'noleap') d = datetimex(2000, 2, 3, calendar='') self.assertEqual(d.replace(year=1999).calendar, '') def test_pickling(self): "Test reversibility of pickling." import pickle date = Datetime360Day(year=1, month=2, day=3, hour=4, minute=5, second=6, microsecond=7) deserialized = pickle.loads(pickle.dumps(date)) self.assertEqual(date, deserialized) self.assertEqual(type(date), type(deserialized)) date = datetimex(1, 2, 3, 4, 5, 6, 7, calendar="360_day") deserialized = pickle.loads(pickle.dumps(date)) self.assertEqual(date, deserialized) self.assertEqual(type(date), type(deserialized)) def test_misc(self): "Miscellaneous tests." # make sure repr succeeds repr(self.date1_365_day) # make sure strftime without a format string works self.assertEqual(self.date3_gregorian.strftime(None), "1969-07-20 12:00:00") def invalid_year(): with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) DatetimeGregorian(0, 1, 1, has_year_zero=False) + self.delta def invalid_month(): DatetimeGregorian(1, 13, 1) + self.delta def invalid_day(): DatetimeGregorian(1, 1, 32) + self.delta def invalid_gregorian_date(): DatetimeGregorian(1582, 10, 5) + self.delta for func in [invalid_year, invalid_month, invalid_day, invalid_gregorian_date]: self.assertRaises(ValueError, func) def test_richcmp(self): # compare datetime and datetime self.assertTrue(self.date1_365_day == self.date1_365_day) self.assertFalse(self.date1_365_day == self.date2_365_day) self.assertTrue(self.date1_365_day < self.date2_365_day) self.assertFalse(self.date1_365_day < self.date1_365_day) self.assertTrue(self.date2_365_day > self.date1_365_day) self.assertFalse(self.date1_365_day > self.date2_365_day) # compare real_datetime and datetime self.assertTrue(self.datetime_date1 > self.date3_gregorian) # compare datetime and real_datetime self.assertFalse(self.date3_gregorian > self.datetime_date1) # compare different calendars (uses change_calendar method) self.assertTrue(self.date3_gregorian_yearzero == self.date3_gregorian) self.assertTrue(self.date4_proleptic_gregorian == self.date4_julian) def not_comparable_1(): "compare two datetime instances with different calendars" self.date1_365_day > self.date3_gregorian def not_comparable_2(): "compare a datetime instance with a non-standard calendar to real_datetime" self.date2_365_day > self.datetime_date1 def not_comparable_3(): "compare datetime.datetime to cftime.datetime with a non-gregorian calendar" self.datetime_date1 > self.date2_365_day def not_comparable_4(): "compare a datetime instance to non-datetime" self.date1_365_day > 0 def not_comparable_5(): "compare non-datetime to a datetime instance" 0 < self.date1_365_day for func in [not_comparable_1, not_comparable_2, not_comparable_3, not_comparable_4, not_comparable_5]: self.assertRaises(TypeError, func) class issue17TestCase(unittest.TestCase): """Regression tests for issue #17/#669.""" # issue 17 / 699: timezone formats not supported correctly # valid timezone formats are: +-hh, +-hh:mm, +-hhmm def setUp(self): pass def test_parse_date_tz(self): "Test timezone parsing in _parse_date" # these should succeed and are ISO8601 compliant expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 60.0) for datestr in ("2017-05-01 00:00+01:00", "2017-05-01 00:00+0100", "2017-05-01 00:00+01"): d = _parse_date(datestr) assert_equal(d, expected_parsed_date) # some more tests with non-zero minutes, should all be ISO compliant and work expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 85.0) for datestr in ("2017-05-01 00:00+01:25", "2017-05-01 00:00+0125"): d = _parse_date(datestr) assert_equal(d, expected_parsed_date) # these are NOT ISO8601 compliant and should not even be parseable but will be parsed with timezone anyway # because, due to support of other legacy time formats, they are difficult to reject # ATTENTION: only the hours part of this will be parsed, single-digit minutes will be ignored! expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 60.0) for datestr in ("2017-05-01 00:00+01:0", "2017-05-01 00:00+01:", "2017-05-01 00:00+01:5"): d = _parse_date(datestr) assert_equal(d, expected_parsed_date) # these should not even be parseable as datestrings but are parseable anyway with ignored timezone # this is because the module also supports some legacy, non-standard time strings expected_parsed_date = (2017, 5, 1, 0, 0, 0, 0, 0.0) for datestr in ("2017-05-01 00:00+1",): d = _parse_date(datestr) assert_equal(d, expected_parsed_date) class issue57TestCase(unittest.TestCase): """Regression tests for issue #57.""" # issue 57: cftime._cftime._dateparse returns quite opaque error messages that make it difficult to # track down the source of problem def setUp(self): pass def test_parse_incorrect_unitstring(self): 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", "days_since_2017-05-01_00:00"): self.assertRaises( ValueError, cftime._cftime._dateparse, datestr, 'standard') self.assertRaises( ValueError, cftime._cftime.num2date, 1, datestr, 'standard') self.assertRaises( ValueError, cftime._cftime.date2num, datetime(1900, 1, 1, 0), datestr, 'standard') _DATE_TYPES = [DatetimeNoLeap, DatetimeAllLeap, DatetimeJulian, Datetime360Day, DatetimeGregorian, DatetimeProlepticGregorian] @pytest.fixture(params=_DATE_TYPES) def date_type(request): return request.param @pytest.fixture(params=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) def month(request): return request.param @pytest.fixture def days_per_month_non_leap_year(date_type, month): if date_type is Datetime360Day: return [-1, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30][month] if date_type is DatetimeAllLeap: return [-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] else: return [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] @pytest.fixture def days_per_month_leap_year(date_type, month): if date_type is Datetime360Day: return [-1, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30][month] if date_type in [DatetimeGregorian, DatetimeProlepticGregorian, DatetimeJulian, DatetimeAllLeap]: return [-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] else: return [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] def test_zero_year(date_type): # Year 0 is valid in the 360,365 and 366 day and # Proleptic Gregorian calendars by default. with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) if date_type in [DatetimeNoLeap, DatetimeAllLeap, Datetime360Day, DatetimeProlepticGregorian]: date_type(0, 1, 1) else: d=date_type(0,1,1) # has_year_zero=True set if year 0 specified assert d.has_year_zero # (issue #248) with pytest.raises(ValueError): date_type(0, 1, 1, has_year_zero=False) def test_invalid_month(date_type): with pytest.raises(ValueError): date_type(1, 0, 1) with pytest.raises(ValueError): date_type(1, 13, 1) def test_invalid_day_non_leap_year( date_type, month, days_per_month_non_leap_year): with pytest.raises(ValueError): date_type(1, month, days_per_month_non_leap_year + 1) def test_invalid_day_leap_year(date_type, month, days_per_month_leap_year): with pytest.raises(ValueError): date_type(2000, month, days_per_month_leap_year + 1) def test_invalid_day_lower_bound(date_type, month): with pytest.raises(ValueError): date_type(1, month, 0) def test_valid_day_non_leap_year( date_type, month, days_per_month_non_leap_year): date_type(1, month, 1) date_type(1, month, days_per_month_non_leap_year) def test_valid_day_leap_year( date_type, month, days_per_month_leap_year): date_type(2000, month, 1) date_type(2000, month, days_per_month_leap_year) _INVALID_SUB_DAY_TESTS = { 'lower-bound-hour': (1, 1, 1, -1), 'upper-bound-hour': (1, 1, 1, 24), 'lower-bound-minute': (1, 1, 1, 1, -1), 'upper-bound-minute': (1, 1, 1, 1, 60), 'lower-bound-second': (1, 1, 1, 1, 1, -1), 'upper-bound-second': (1, 1, 1, 1, 1, 60), 'lower-bound-microsecond': (1, 1, 1, 1, 1, 1, -1), 'upper-bound-microsecond': (1, 1, 1, 1, 1, 1, 1000000) } @pytest.mark.parametrize('date_args', list(_INVALID_SUB_DAY_TESTS.values()), ids=list(_INVALID_SUB_DAY_TESTS.keys())) def test_invalid_sub_day_reso_dates(date_type, date_args): with pytest.raises(ValueError): date_type(*date_args) _VALID_SUB_DAY_TESTS = { 'lower-bound-hour': (1, 1, 1, 0), 'upper-bound-hour': (1, 1, 1, 23), 'lower-bound-minute': (1, 1, 1, 1, 0), 'upper-bound-minute': (1, 1, 1, 1, 59), 'lower-bound-second': (1, 1, 1, 1, 1, 0), 'upper-bound-second': (1, 1, 1, 1, 1, 59), 'lower-bound-microsecond': (1, 1, 1, 1, 1, 1, 0), 'upper-bound-microsecond': (1, 1, 1, 1, 1, 1, 999999) } @pytest.mark.parametrize('date_args', list(_VALID_SUB_DAY_TESTS.values()), ids=list(_VALID_SUB_DAY_TESTS.keys())) def test_valid_sub_day_reso_dates(date_type, date_args): date_type(*date_args) @pytest.mark.parametrize( 'date_args', [(1582, 10, 5), (1582, 10, 14)], ids=['lower-bound', 'upper-bound']) def test_invalid_julian_gregorian_mixed_dates(date_type, date_args): if date_type is DatetimeGregorian: with pytest.raises(ValueError): date_type(*date_args) else: date_type(*date_args) @pytest.mark.parametrize( 'date_args', [(1582, 10, 4), (1582, 10, 15)], ids=['lower-bound', 'upper-bound']) def test_valid_julian_gregorian_mixed_dates(date_type, date_args): date_type(*date_args) @pytest.mark.parametrize( 'date_args', [(1, 2, 3, 4, 5, 6), (10, 2, 3, 4, 5, 6), (100, 2, 3, 4, 5, 6), (1000, 2, 3, 4, 5, 6), (2000, 1, 1, 12, 34, 56, 123456)], ids=['1', '10', '100', '1000', '2000']) def test_str_matches_datetime_str(date_type, date_args): assert str(date_type(*date_args)) == str(datetime(*date_args)) _EXPECTED_DATE_TYPES = {'noleap': DatetimeNoLeap, '365_day': DatetimeNoLeap, '360_day': Datetime360Day, 'julian': DatetimeJulian, 'all_leap': DatetimeAllLeap, '366_day': DatetimeAllLeap, 'gregorian': DatetimeGregorian, 'proleptic_gregorian': DatetimeProlepticGregorian, 'standard': DatetimeGregorian} @pytest.mark.parametrize( ['calendar', 'expected_date_type'], list(_EXPECTED_DATE_TYPES.items()) ) def test_num2date_only_use_cftime_datetimes_negative_years( calendar, expected_date_type): with warnings.catch_warnings(): warnings.simplefilter("ignore",category=cftime.CFWarning) result = num2date(-1000., units='days since 0001-01-01', calendar=calendar, only_use_cftime_datetimes=True) assert isinstance(result, datetimex) assert (result.calendar == adjust_calendar(calendar)) @pytest.mark.parametrize( ['calendar', 'expected_date_type'], list(_EXPECTED_DATE_TYPES.items()) ) def test_num2date_only_use_cftime_datetimes_pre_gregorian( calendar, expected_date_type): result = num2date(1., units='days since 0001-01-01', calendar=calendar, only_use_cftime_datetimes=True) assert isinstance(result, datetimex) assert (result.calendar == adjust_calendar(calendar)) @pytest.mark.parametrize( ['calendar', 'expected_date_type'], list(_EXPECTED_DATE_TYPES.items()) ) def test_num2date_only_use_cftime_datetimes_post_gregorian( calendar, expected_date_type): result = num2date(0., units='days since 1582-10-15', calendar=calendar, only_use_cftime_datetimes=True) assert isinstance(result, datetimex) assert (result.calendar == adjust_calendar(calendar)) def test_repr(): expected = "cftime.datetime(2000, 1, 1, 0, 0, 0, 0, calendar='standard', has_year_zero=False)" assert repr(datetimex(2000, 1, 1, calendar='standard')) == expected expected = "cftime.datetime(2000, 1, 1, 0, 0, 0, 0, calendar='', has_year_zero=False)" assert repr(datetimex(2000, 1, 1, calendar=None)) == expected def test_string_format(): dt = cftime.datetime(2000, 1, 1) # check the default formatting is the same as strftime assert dt.strftime() == '{0}'.format(dt) # check a given format string acts like strftime assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt) assert 'the year is 2000' == 'the year is {dt:%Y}'.format(dt=dt) def test_string_format2(): dt = cftime.datetime(-4713, 1, 1, 12, 0, 0, 10) # check a given format string acts like strftime assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt) assert dt.strftime() == '-4713-01-01 12:00:00' assert dt.strftime('%Y-%m-%d %H:%M:%S') == '-4713-01-01 12:00:00' assert dt.strftime('%Y-%m-%d %H:%M:%S.%f') == '-4713-01-01 12:00:00.000010' assert dt.strftime('%d.%m.%Y %H:%M:%S.%f') == '01.01.-4713 12:00:00.000010' dt = cftime.datetime(-713, 1, 1, 12, 0, 0, 10) assert dt.strftime('%H%m%d') == '{0:%H%m%d}'.format(dt) assert dt.strftime() == '-0713-01-01 12:00:00' assert dt.strftime('%Y-%m-%d %H:%M:%S') == '-0713-01-01 12:00:00' assert dt.strftime('%Y-%m-%d %H:%M:%S.%f') == '-0713-01-01 12:00:00.000010' assert dt.strftime('%d.%m.%Y %H:%M:%S.%f') == '01.01.-0713 12:00:00.000010' def test_strptime(): d = cftime.datetime.strptime('24/Aug/2004:17:57:26 +0200', '%d/%b/%Y:%H:%M:%S %z',calendar='julian',has_year_zero=True) assert repr(d) == "cftime.datetime(2004, 8, 24, 15, 57, 26, 0, calendar='julian', has_year_zero=True)" d = cftime.datetime.strptime("0000-02-30",\ "%Y-%m-%d",calendar='360_day',has_year_zero=True) assert repr(d) == "cftime.datetime(0, 2, 30, 0, 0, 0, 0, calendar='360_day', has_year_zero=True)" d = cftime.datetime.strptime('-9999-02-29 10:18:32.926',\ '%Y-%m-%d %H:%M:%S.%f',calendar='366_day') assert repr(d) == "cftime.datetime(-9999, 2, 29, 10, 18, 32, 926000, calendar='all_leap', has_year_zero=True)" d = cftime.datetime.strptime("20200230", "%Y%m%d", "360_day") # no separator, issue #301 assert repr(d) == "cftime.datetime(2020, 2, 30, 0, 0, 0, 0, calendar='360_day', has_year_zero=True)" d = cftime.datetime.strptime('24/Aug/-4712:17:57:26', '%d/%b/%Y:%H:%M:%S',calendar='julian') assert repr(d) == "cftime.datetime(-4712, 8, 24, 17, 57, 26, 0, calendar='julian', has_year_zero=False)" d = cftime.datetime.strptime('24/August/-4712:17:57:26', '%d/%B/%Y:%H:%M:%S',calendar='julian') assert repr(d) == "cftime.datetime(-4712, 8, 24, 17, 57, 26, 0, calendar='julian', has_year_zero=False)" d = cftime.datetime.strptime("-4712", "%Y", calendar="julian") assert repr(d) == "cftime.datetime(-4712, 1, 1, 0, 0, 0, 0, calendar='julian', has_year_zero=False)" # should fail with KeyError try: d=cftime.datetime.strptime("2000-45-3", "%G-%V-%u", calendar="noleap") except KeyError: pass else: raise AssertionError def test_string_isoformat(): dt = cftime.datetime(-4713, 1, 1, 12, 0, 0, 10) assert dt.isoformat() == '-4713-01-01T12:00:00.000010' assert dt.isoformat(' ', 'days') == '-4713-01-01' assert dt.isoformat(' ', 'seconds') == '-4713-01-01 12:00:00' assert dt.isoformat(' ', 'microseconds') == '-4713-01-01 12:00:00.000010' dt = cftime.datetime(-713, 1, 1, 12, 0, 0, 10) assert dt.isoformat() == '-0713-01-01T12:00:00.000010' assert dt.isoformat(' ', 'days') == '-0713-01-01' assert dt.isoformat(' ', 'seconds') == '-0713-01-01 12:00:00' assert dt.isoformat(' ', 'microseconds') == '-0713-01-01 12:00:00.000010' def test_dayofyr_after_replace(date_type): date = date_type(1, 1, 1) assert date.dayofyr == 1 assert date.replace(day=2).dayofyr == 2 def test_dayofwk_after_replace(date_type): date = date_type(1, 1, 1) original_dayofwk = date.dayofwk expected = (original_dayofwk + 1) % 7 result = date.replace(day=2).dayofwk assert result == expected def test_daysinmonth_non_leap(date_type, month, days_per_month_non_leap_year): date = date_type(1, month, 1) assert date.daysinmonth == days_per_month_non_leap_year def test_daysinmonth_leap(date_type, month, days_per_month_leap_year): date = date_type(2000, month, 1) assert date.daysinmonth == days_per_month_leap_year @pytest.mark.parametrize('argument', ['dayofyr', 'dayofwk']) def test_replace_dayofyr_or_dayofwk_error(date_type, argument): with pytest.raises(ValueError): date_type(1, 1, 1).replace(**{argument: 3}) def test_dayofyr_after_timedelta_addition(date_type): initial_date = date_type(1, 1, 2) date_after_timedelta_addition = initial_date + timedelta(days=1) assert initial_date.dayofyr == 2 assert date_after_timedelta_addition.dayofyr == 3 def test_exact_datetime_difference(date_type): b = date_type(2000, 1, 2, 0, 0, 0, 5) a = date_type(2000, 1, 2) result = b - a expected = timedelta(microseconds=5) assert result == expected _SHAPES = [(4, ), (2, 2)] _MICROSECOND_UNITS = ["microseconds", "microsecond", "microsec", "microsecs"] _MILLISECOND_UNITS = ["milliseconds", "millisecond", "millisec", "millisecs", "ms"] _SECOND_UNITS = ["seconds", "second", "sec", "secs", "s"] _MINUTE_UNITS = ["minutes", "minute", "min", "mins"] _HOUR_UNITS = ["hours", "hour", "hr", "hrs", "h"] _DAY_UNITS = ["day", "days", "d"] _MONTH_UNITS = ["month", "months"] _YEAR_UNITS = ["common_years", "common_year"] _DTYPES = [np.dtype("int64"), np.dtype("float64")] _STANDARD_CALENDARS = [ "standard", "gregorian", "proleptic_gregorian" ] _REAL_WORLD_CALENDARS = [ "julian", "standard", "gregorian", "proleptic_gregorian" ] _NO_YEAR_ZERO_CALENDARS = [ "julian", "standard", "gregorian", ] _ARTIFICIAL_CALENDARS = ["noleap", "all_leap", "360_day"] @pytest.fixture(params=_SHAPES) def shape(request): return request.param @pytest.fixture(params=_DTYPES) def dtype(request): return request.param @pytest.fixture(params=list(_EXPECTED_DATE_TYPES.keys())) def calendar(request): return request.param @pytest.mark.parametrize("unit", _MICROSECOND_UNITS) def test_num2date_microsecond_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 0, 0, 0, 1), date_type(2000, 1, 1, 0, 0, 0, 2), date_type(2000, 1, 1, 0, 0, 0, 3), date_type(2000, 1, 1, 0, 0, 0, 4)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _MILLISECOND_UNITS) def test_num2date_millisecond_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 0, 0, 0, 1000), date_type(2000, 1, 1, 0, 0, 0, 2000), date_type(2000, 1, 1, 0, 0, 0, 3000), date_type(2000, 1, 1, 0, 0, 0, 4000)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _SECOND_UNITS) def test_num2date_second_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 0, 0, 1, 0), date_type(2000, 1, 1, 0, 0, 2, 0), date_type(2000, 1, 1, 0, 0, 3, 0), date_type(2000, 1, 1, 0, 0, 4, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _MINUTE_UNITS) def test_num2date_minute_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 0, 1, 0, 0), date_type(2000, 1, 1, 0, 2, 0, 0), date_type(2000, 1, 1, 0, 3, 0, 0), date_type(2000, 1, 1, 0, 4, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _HOUR_UNITS) def test_num2date_hour_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0), date_type(2000, 1, 1, 2, 0, 0, 0), date_type(2000, 1, 1, 3, 0, 0, 0), date_type(2000, 1, 1, 4, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _DAY_UNITS) def test_num2date_day_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0), date_type(2000, 1, 3, 0, 0, 0, 0), date_type(2000, 1, 4, 0, 0, 0, 0), date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _MONTH_UNITS) def test_num2date_month_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 2, 1, 0, 0, 0, 0), date_type(2000, 3, 1, 0, 0, 0, 0), date_type(2000, 4, 1, 0, 0, 0, 0), date_type(2000, 5, 1, 0, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) if calendar != "360_day": with pytest.raises(ValueError): num2date(numeric_times, units=units, calendar=calendar) else: result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) @pytest.mark.parametrize("unit", _YEAR_UNITS) def test_num2date_year_units(calendar, unit, shape, dtype): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2001, 1, 1, 0, 0, 0, 0), date_type(2002, 1, 1, 0, 0, 0, 0), date_type(2003, 1, 1, 0, 0, 0, 0), date_type(2004, 1, 1, 0, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "{} since 2000-01-01".format(unit) if calendar not in {"365_day", "noleap"}: with pytest.raises(ValueError): num2date(numeric_times, units=units, calendar=calendar) else: result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) def test_num2date_only_use_python_datetimes(calendar, shape, dtype): date_type = real_datetime expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0), date_type(2000, 1, 3, 0, 0, 0, 0), date_type(2000, 1, 4, 0, 0, 0, 0), date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "days since 2000-01-01" if calendar not in _STANDARD_CALENDARS: with pytest.raises(ValueError): num2date(numeric_times, units=units, calendar=calendar, only_use_python_datetimes=True, only_use_cftime_datetimes=False) else: result = num2date(numeric_times, units=units, calendar=calendar, only_use_python_datetimes=True, only_use_cftime_datetimes=False) np.testing.assert_equal(result, expected) def test_num2date_use_pydatetime_if_possible(calendar, shape, dtype): if calendar not in _STANDARD_CALENDARS: date_type = _EXPECTED_DATE_TYPES[calendar] else: date_type = real_datetime expected = np.array([date_type(2000, 1, 2, 0, 0, 0, 0), date_type(2000, 1, 3, 0, 0, 0, 0), date_type(2000, 1, 4, 0, 0, 0, 0), date_type(2000, 1, 5, 0, 0, 0, 0)]).reshape(shape) numeric_times = np.array([1, 2, 3, 4]).reshape(shape).astype(dtype) units = "days since 2000-01-01" result = num2date(numeric_times, units=units, calendar=calendar, only_use_python_datetimes=False, only_use_cftime_datetimes=False) np.testing.assert_equal(result, expected) @pytest.mark.parametrize( ["standard_calendar", "breakpoint"], [("proleptic_gregorian", "{}-12-31T23:59:59.999999".format(MINYEAR - 1)), ("gregorian", "1582-10-15"), ("standard", "1582-10-15")] ) def test_num2date_only_use_python_datetimes_invalid_basedate( standard_calendar, breakpoint ): units = "days since {}".format(breakpoint) numeric_times = np.array([1, 2, 3, 4]) with pytest.raises(ValueError): num2date( numeric_times, units=units, calendar=standard_calendar, only_use_python_datetimes=True, only_use_cftime_datetimes=False ) @pytest.mark.parametrize("real_world_calendar", _NO_YEAR_ZERO_CALENDARS) def test_num2date_invalid_zero_reference_year(real_world_calendar): units = "days since 0000-01-01" numeric_times = np.array([1, 2, 3, 4]) with pytest.raises(ValueError, match="zero not allowed as a reference"): num2date( numeric_times, units=units, calendar=real_world_calendar ) @pytest.mark.parametrize("artificial_calendar", _ARTIFICIAL_CALENDARS) def test_num2date_valid_zero_reference_year(artificial_calendar): units = "days since 0000-01-01" numeric_times = np.array([1, 2, 3, 4]) num2date(numeric_times, units=units, calendar=artificial_calendar) def test_num2date_masked_array(calendar): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0), date_type(2000, 1, 1, 2, 0, 0, 0), date_type(2000, 1, 1, 3, 0, 0, 0), date_type(2000, 1, 1, 4, 0, 0, 0)]) mask = [False, False, True, False] expected = np.ma.masked_array(expected, mask=mask) numeric_times = np.ma.masked_array([1, 2, 3, 4], mask=mask) units = "hours since 2000-01-01" result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) def test_num2date_out_of_range(): numeric_times = 12 * np.array([200000, 400000, 600000]) units = "months since 2000-01-01" with pytest.raises(OverflowError, match="time values outside range of 64 bit signed integers"): num2date(numeric_times, units=units, calendar="360_day") def test_num2date_list_input(calendar): date_type = _EXPECTED_DATE_TYPES[calendar] expected = np.array([date_type(2000, 1, 1, 1, 0, 0, 0), date_type(2000, 1, 1, 2, 0, 0, 0), date_type(2000, 1, 1, 3, 0, 0, 0), date_type(2000, 1, 1, 4, 0, 0, 0)]) numeric_times = [1, 2, 3, 4] units = "hours since 2000-01-01" result = num2date(numeric_times, units=units, calendar=calendar) np.testing.assert_equal(result, expected) def test_num2date_integer_upcast_required(): numeric_times = np.array([30, 60, 90, 120], dtype=np.int32) units = "minutes since 2000-01-01" expected = np.array([ Datetime360Day(2000, 1, 1, 0, 30, 0), Datetime360Day(2000, 1, 1, 1, 0, 0), Datetime360Day(2000, 1, 1, 1, 30, 0), Datetime360Day(2000, 1, 1, 2, 0, 0) ]) result = num2date(numeric_times, units=units, calendar="360_day") np.testing.assert_equal(result, expected) @pytest.mark.parametrize( "encoding_units", ["microseconds", "milliseconds", "seconds", "minutes", "hours", "days"] ) @pytest.mark.parametrize( "freq", [ timedelta(microseconds=1), timedelta(microseconds=1000), timedelta(seconds=1), timedelta(minutes=1), timedelta(hours=1), timedelta(days=1) ], ids=lambda x: f"{x!r}" ) def test_date2num_num2date_roundtrip(encoding_units, freq, calendar): date_type = _EXPECTED_DATE_TYPES[calendar] lengthy_timedelta = timedelta(days=291000 * 360) times = np.array( [ date_type(1, 1, 1), date_type(1, 1, 1) + lengthy_timedelta, date_type(1, 1, 1) + lengthy_timedelta + freq ] ) units = f"{encoding_units} since 0001-01-01" encoded = date2num(times, units=units, calendar=calendar) decoded = num2date(encoded, units=units, calendar=calendar) encoding_units_as_timedelta = timedelta(microseconds=UNIT_CONVERSION_FACTORS[encoding_units]) if freq >= encoding_units_as_timedelta: assert encoded.dtype == np.int64 np.testing.assert_equal(decoded, times) else: # if sys.platform.startswith("win"): # assert encoded.dtype == np.float64 # else: # assert encoded.dtype == np.float128 assert encoded.dtype == np.float64 tolerance = timedelta(microseconds=2000) meets_tolerance = np.abs(decoded - times) <= tolerance assert np.all(meets_tolerance) def test_date2num_missing_data(): # Masked array a = [ cftime.DatetimeGregorian(2000, 12, 1), cftime.DatetimeGregorian(2000, 12, 2), cftime.DatetimeGregorian(2000, 12, 3), cftime.DatetimeGregorian(2000, 12, 4), ] mask = [True, False, True, False] array = np.ma.array(a, mask=mask) out = date2num(array, units="days since 2000-12-01", calendar="standard") assert ((out == np.ma.array([-99, 1, -99, 3], mask=mask)).all()) assert ((out.mask == mask).all()) # Scalar masked array a = cftime.DatetimeGregorian(2000, 12, 1) mask = True array = np.ma.array(a, mask=mask) out = date2num(array, units="days since 2000-12-01", calendar="standard") assert out is np.ma.masked def test_date2num_numpy_datetime64(): # Array array = np.array([ np.datetime64(123, "s"), np.datetime64(124, "s"), np.datetime64(125, "s") ]) out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian") assert ((out == np.array([123, 124, 125]))).all() # Scalar array = np.datetime64(123, "s") out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian") assert out == np.int64(123) def test_num2date_preserves_shape(): # The optimized num2date algorithm operates on a flattened array. This # check ensures that the original shape of the times is restored in the # result. a = np.array([[0, 1, 2], [3, 4, 5]]) result = num2date(a, units="days since 2000-01-01", calendar="standard") expected = np.array([cftime.DatetimeGregorian(2000, 1, i) for i in range(1, 7)]).reshape((2, 3)) np.testing.assert_equal(result, expected) def test_num2date_preserves_order(): # The optimized num2date algorithm sorts the encoded times before decoding them. # This check ensures that the order of the times is restored in the result. a = np.array([1, 0]) result = num2date(a, units="days since 2000-01-01", calendar="standard") expected = np.array([cftime.DatetimeGregorian(2000, 1, i) for i in [2, 1]]) np.testing.assert_equal(result, expected) def test_num2date_empty_array(): a = np.array([[]]) result = num2date(a, units="days since 2000-01-01", calendar="standard") expected = np.array([[]], dtype="O") np.testing.assert_equal(result, expected) DATEPARSE_ERROR_TESTS = [ ("foo", "In general, units must be"), ("months", "'months since' units only allowed"), ("common_years", "'common_years' units only allowed") ] @pytest.mark.parametrize(("units", "match"), DATEPARSE_ERROR_TESTS) def test_num2date_unrecognized_units(units, match): with pytest.raises(ValueError, match=match): num2date(0.0, units=f"{units} since 2000-01-01", calendar="standard") @pytest.mark.parametrize(("units", "match"), DATEPARSE_ERROR_TESTS) def test_date2num_unrecognized_units(units, match): date = cftime.datetime(2000, 1, 1, calendar="standard") with pytest.raises(ValueError, match=match): date2num(date, units=f"{units} since 2000-01-01", calendar="standard") def test_num2date_precision(): if np.finfo(np.longdouble).precision < 18: pytest.skip("skipping tests that require extended precision longdouble type") testdates = [(1271, 3, 18, 19, 41, 33), (1271, 3, 18, 19, 41, 32, 999998)] unitinc = ['microseconds', 'seconds', 'minutes', 'hours', 'days'] for cc in ['standard', 'gregorian', 'julian', 'proleptic_gregorian', 'noleap', 'all_leap', '365_day', '366_day', '360_day']: for uinc in unitinc: if cc in ['standard', 'gregorian', 'julian']: units = uinc + ' since -4713-01-01 12:00:00' elif cc in ['proleptic_gregorian']: units = uinc + ' since -4714-01-01 12:00:00' elif cc in ['noleap', 'all_leap', '365_day', '366_day', '360_day']: units = uinc + ' since 0000-01-01 12:00:00' # scalar date = datetimex(*testdates[0], calendar=cc) num = date2num(date, units, calendar=cc, longdouble=True) date2 = num2date(num, units, calendar=cc) assert date == date2 # array date = [ datetimex(*dd, calendar=cc) for dd in testdates ] num = date2num(date, units, calendar=cc, longdouble=True) date2 = num2date(num, units, calendar=cc) for i in range(len(date)): assert date[i] == date2[i] # masked array num = np.ma.array(num, mask=(True, False)) date2 = num2date(num, units, calendar=cc) assert np.ma.is_masked(date2[0]) assert date[1] == date2[1] # NOTE: using pytest style tests -- these won't run without pytest # but it looks like you're using pytest, so this is cleaner and easier # There's really no reason to put these in a class, but it does organize things class Test_tai: """ tests specific to the tai calendar """ def test_dateparse_valid(self): """ It should raise for an epoch before 1958 """ # This is directly testing the _dateparse function # Which is a "proper" unit test, but also testing an internal function. timestring = "seconds since 1958-01-01T00:00:00" basedate = cftime._dateparse(timestring, 'tai') print(repr(basedate)) assert basedate == cftime.datetime(1958, 1, 1, 0, 0, 0, 0, calendar='tai', has_year_zero=False) def test_dateparse_before_1958(self): """ It should raise for an epoch before 1958 """ # This is directly testing the _dateparse function # Which is a "proper" unit test, but also testing an internal function. timestring = "seconds since 1957-01-01T00:00:00" with pytest.raises(ValueError): basedate = cftime._dateparse(timestring, 'tai') # cftime._dateparse(timestring, 'tai', has_year_zero=None) print(basedate) def test_dateparse_with_offset(self): """ It should raise if there's an offset """ # This is directly testing the _dateparse function # Which is a "proper" unit test, but also testing an internal function. timestring = "seconds since 1965-01-01T00:00:00+08:00" with pytest.raises(ValueError): basedate = cftime._dateparse(timestring, 'tai') # cftime._dateparse(timestring, 'tai', has_year_zero=None) print(basedate) def test_year_zero(self): """ tai does not have a year zero -- not sure this is worth testing, but for full coverage. """ # This is directly testing the _dateparse function # Which is a "proper" unit test, but also testing an internal function. timestring = "seconds since 1965-01-01T00:00:00" with pytest.raises(ValueError): basedate = cftime._dateparse(timestring, 'tai', has_year_zero=True) # cftime._dateparse(timestring, 'tai', has_year_zero=None) print(basedate) def test_creation_valid(self): dt = DatetimeTAI(2025, 1, 9, 14, 18) assert dt.calendar == 'tai' assert dt.has_year_zero is False print(repr(dt)) def test_creation_before_1958(self): with pytest.raises(ValueError): dt = DatetimeTAI(1957, 1, 9, 14, 18) print(repr(dt)) if __name__ == '__main__': unittest.main()