How to use the cftime.date2num function in cftime

To help you get started, we’ve selected a few cftime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Unidata / cftime / test / test_cftime.py View on Github external
maxerr = 0
            for n in range(ntimes):
                microsecs1 += 1.
                date1 = num2date(microsecs1, units, calendar=calendar)
                microsecs2 = date2num(date1, units, calendar=calendar)
                date2 = num2date(microsecs2, units, calendar=calendar)
                err = np.abs(microsecs1 - microsecs2)
                maxerr = max(err,maxerr)
                assert(err < eps)
                assert(date1.strftime(dateformat) == date2.strftime(dateformat))
            if verbose:
                print('calendar = %s max abs err (microsecs) = %s eps = %s' % \
                     (calendar,maxerr,eps))
            units = 'milliseconds since 1800-01-30 01:01:01'
            eps = 0.001
            millisecs1 = date2num(dateref,units,calendar=calendar)
            maxerr = 0.
            for n in range(ntimes):
                millisecs1 += 0.001
                date1 = num2date(millisecs1, units, calendar=calendar)
                millisecs2 = date2num(date1, units, calendar=calendar)
                date2 = num2date(millisecs2, units, calendar=calendar)
                err = np.abs(millisecs1 - millisecs2)
                maxerr = max(err,maxerr)
                assert(err < eps)
                assert(date1.strftime(dateformat) == date2.strftime(dateformat))
            if verbose:
                print('calendar = %s max abs err (millisecs) = %s eps = %s' % \
                     (calendar,maxerr,eps))
            eps = 1.e-5
            units = 'seconds since 0001-01-30 01:01:01'
            secs1 = date2num(dateref,units,calendar=calendar)
github Unidata / cftime / test / test_cftime.py View on Github external
err = np.abs(mins1 - mins2)
                maxerr = max(err,maxerr)
                assert(err < eps)
                diff = abs(date1-date2)
                assert(diff.microseconds < 100)
            if verbose:
                print('calendar = %s max abs err (mins) = %s eps = %s' % \
                     (calendar,maxerr,eps))
            eps = 1.e-8
            units = 'hours since 0001-01-30 01:01:01'
            hrs1 = date2num(dateref,units,calendar=calendar)
            maxerr = 0.
            for n in range(ntimes):
                hrs1 += 0.001
                date1 = num2date(hrs1, units, calendar=calendar)
                hrs2 = date2num(date1, units, calendar=calendar)
                date2 = num2date(hrs2, units, calendar=calendar)
                err = np.abs(hrs1 - hrs2)
                maxerr = max(err,maxerr)
                assert(err < eps)
                diff = abs(date1-date2)
                assert(diff.microseconds < 100)
            if verbose:
                print('calendar = %s max abs err (hours) = %s eps = %s' % \
                     (calendar,maxerr,eps))
            eps = 1.e-9
            units = 'days since 0001-01-30 01:01:01'
            days1 = date2num(dateref,units,calendar=calendar)
            maxerr = 0.
            for n in range(ntimes):
                days1 += 0.00001
                date1 = num2date(days1, units, calendar=calendar)
github Unidata / cftime / test / test_cftime.py View on Github external
self.assertEqual(d1, d2)
            self.assertEqual(num2date(d1, units, cap_cal),
                             num2date(d1, units, low_cal))
        # issue 415
        t = datetimex(2001, 12, 1, 2, 3, 4)
        self.assertEqual(t, copy.deepcopy(t))

        # issue 442
        units = "days since 0000-01-01 00:00:00"
        # this should fail (year zero not allowed with real-world calendars)
        try:
            date2num(datetime(1, 1, 1), units, calendar='standard')
        except ValueError:
            pass
        # this should not fail (year zero allowed in 'fake' calendars)
        t = date2num(datetime(1, 1, 1), units, calendar='360_day')
        self.assertAlmostEqual(t,360)
        d = num2date(t, units, calendar='360_day')
        self.assertEqual(d, Datetime360Day(1,1,1))
        d = num2date(0, units, calendar='360_day')
        self.assertEqual(d, Datetime360Day(0,1,1))

        # issue 685: wrong time zone conversion
        # 'The following times all refer to the same moment: "18:30Z", "22:30+04", "1130-0700", and "15:00-03:30'
        # (https://en.wikipedia.org/w/index.php?title=ISO_8601&oldid=787811367#Time_offsets_from_UTC)
        # test num2date
        utc_date = datetime(2000,1,1,18,30)
        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"):
            d = num2date(0, units, calendar="standard")
            #self.assertEqual(d, utc_date)
            # tolerance of 1.e-3 secs
            assert(np.abs((d-utc_date).total_seconds()) < 1.e-3)
github Unidata / cftime / test / test_cftime.py View on Github external
assert_equal(t, 365)

        # Test dates outside the support with after
        t = date2index(datetime(1949, 12, 1), nutime, select='after')
        assert_equal(t, 0)

        self.assertRaises(
            ValueError, date2index, datetime(1978, 1, 1), nutime, select='after')
        # test microsecond and millisecond units
        unix_epoch = "milliseconds since 1970-01-01T00:00:00Z"
        d = datetime(2038, 1, 19, 3, 14, 7)
        millisecs = int(
            date2num(d, unix_epoch, calendar='proleptic_gregorian'))
        assert_equal(millisecs, (2 ** 32 / 2 - 1) * 1000)
        unix_epoch = "microseconds since 1970-01-01T00:00:00Z"
        microsecs = int(date2num(d, unix_epoch))
        assert_equal(microsecs, (2 ** 32 / 2 - 1) * 1000000)
        # test microsecond accuracy in date2num/num2date roundtrip
        # note: microsecond accuracy lost for time intervals greater
        # than about 270 years.
        units = 'microseconds since 1776-07-04 00:00:00-12:00'
        dates = [datetime(1962, 10, 27, 6, 1, 30, 9001),
                 datetime(1993, 11, 21, 12, 5, 25, 999),
                 datetime(1995, 11, 25, 18, 7, 59, 999999)]
        times2 = date2num(dates, units)
        dates2 = num2date(times2, units)
        for date, date2 in zip(dates, dates2):
            assert_equal(date, date2)
github Unidata / cftime / test / test_cftime.py View on Github external
assert_almost_equal(t, 2446068)

        # issue #68: allow months since for 360_day calendar
        d = num2date(1, 'months since 0000-01-01 00:00:00', calendar='360_day')
        self.assertEqual(d, Datetime360Day(0,2,1))
        t = date2num(d, 'months since 0000-01-01 00:00:00', calendar='360_day')
        self.assertEqual(t, 1)
        # check that exception is raised if 'months since' used with
        # anything but the 360_day calendar.
        self.assertRaises(ValueError, num2date, \
             1, 'months since 01-01-01',calendar='standard')
        self.assertRaises(ValueError, utime, \
            'months since 01-01-01', calendar='standard')
        # issue #78 - extra digits due to roundoff
        assert(cftime.date2num(cftime.datetime(1, 12, 1, 0, 0, 0, 0, -1, 1), units='days since 01-01-01',calendar='noleap')  == 334.0)
        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)
        assert(cftime.date2num(cftime.DatetimeNoLeap(1980, 1, 1, 0, 0, 0, 0, 6, 1),'days since 1970-01-01','noleap') == 3650.0)
github Unidata / cftime / test / test_cftime.py View on Github external
d1 = datetimex(2020, 5, 20, calendar='')
        assert (d1.dayofwk == d1.dayofyr == -1)
        d1 = datetimex(2020, 5, 20, dayofwk=-2, dayofyr=-3, calendar='')
        assert (d1.dayofwk == -2)
        assert (d1.dayofyr == -3)
        d1 = datetimex(2020, 5, 20, dayofwk=8, dayofyr=9, calendar='')
        assert (d1.dayofwk == 8)
        assert (d1.dayofyr == 9)
        
        # issue 71: negative reference years
        # https://coastwatch.pfeg.noaa.gov/erddap/convert/time.html
        # gives 2446433 (365 days more - is it counting year 0?)
        # however http://aa.usno.navy.mil/data/docs/JulianDate.php gives
        # 2446068, which agrees with us
        units = "days since -4713-01-01T00:00:00Z"
        t = date2num(datetime(1985,1,2), units, calendar="standard")
        assert_almost_equal(t, 2446068)

        # issue #68: allow months since for 360_day calendar
        d = num2date(1, 'months since 0000-01-01 00:00:00', calendar='360_day')
        self.assertEqual(d, Datetime360Day(0,2,1))
        t = date2num(d, 'months since 0000-01-01 00:00:00', calendar='360_day')
        self.assertEqual(t, 1)
        # check that exception is raised if 'months since' used with
        # anything but the 360_day calendar.
        self.assertRaises(ValueError, num2date, \
             1, 'months since 01-01-01',calendar='standard')
        self.assertRaises(ValueError, utime, \
            'months since 01-01-01', calendar='standard')
        # issue #78 - extra digits due to roundoff
        assert(cftime.date2num(cftime.datetime(1, 12, 1, 0, 0, 0, 0, -1, 1), units='days since 01-01-01',calendar='noleap')  == 334.0)
        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)
github openstreams / wflow / wflow / wf_netcdfio.py View on Github external
if units == None:  # Use start of the run
        epoch = timeList[0]
        units = "seconds since %04d-%02d-%02d %02d:%02d:%02d.0 00:00" % (
            epoch.year,
            epoch.month,
            epoch.day,
            epoch.hour,
            epoch.minute,
            epoch.second,
        )

    startDayNr = cftime.date2num(
        timeList[0].replace(tzinfo=None), units=units, calendar=calendar
    )
    endDayNr = cftime.date2num(
        timeList[-1].replace(tzinfo=None), units=units, calendar=calendar
    )

    timeAR = linspace(startDayNr, endDayNr, num=len(timeList))

    if os.path.exists(trgFile):
        os.remove(trgFile)

    nc_trg = netCDF4.Dataset(
        trgFile, "w", format=Format, zlib=zlib, complevel=complevel
    )

    logger.info(
        "Setting up dimensions and attributes. Steps: "
        + str(len(timeList))
        + " lat: "
github openstreams / wflow / wflow / wf_netcdfio.py View on Github external
"""

    logger.info("Setting up netcdf output: " + trgFile)

    if units == None:  # Use start of the run
        epoch = timeList[0]
        units = "seconds since %04d-%02d-%02d %02d:%02d:%02d.0 00:00" % (
            epoch.year,
            epoch.month,
            epoch.day,
            epoch.hour,
            epoch.minute,
            epoch.second,
        )

    startDayNr = cftime.date2num(
        timeList[0].replace(tzinfo=None), units=units, calendar=calendar
    )
    endDayNr = cftime.date2num(
        timeList[-1].replace(tzinfo=None), units=units, calendar=calendar
    )

    timeAR = linspace(startDayNr, endDayNr, num=len(timeList))

    if os.path.exists(trgFile):
        os.remove(trgFile)

    nc_trg = netCDF4.Dataset(
        trgFile, "w", format=Format, zlib=zlib, complevel=complevel
    )

    logger.info(
github openstreams / wflow / Scripts / wflow_flood_lib.py View on Github external
def prepare_nc(
    trg_file,
    times,
    x,
    y,
    metadata={},
    logging=logging,
    units="Days since 1900-01-01 00:00:00",
    calendar="gregorian",
):
    """
    This function prepares a NetCDF file with given metadata, for a certain year, daily basis data
    The function assumes a gregorian calendar and a time unit 'Days since 1900-01-01 00:00:00'
    """
    logger.info('Setting up "' + trg_file + '"')
    times_list = cftime.date2num(times, units=units, calendar=calendar)
    nc_trg = nc.Dataset(trg_file, "w")
    logger.info("Setting up dimensions and attributes")
    nc_trg.createDimension("time", 0)  # NrOfDays*8
    nc_trg.createDimension("lat", len(y))
    nc_trg.createDimension("lon", len(x))
    times_nc = nc_trg.createVariable("time", "f8", ("time",))
    times_nc.units = units
    times_nc.calendar = calendar
    times_nc.standard_name = "time"
    times_nc.long_name = "time"
    times_nc[:] = times_list
    y_var = nc_trg.createVariable("lat", "f4", ("lat",))
    y_var.standard_name = "latitude"
    y_var.long_name = "latitude"
    y_var.units = "degrees_north"
    x_var = nc_trg.createVariable("lon", "f4", ("lon",))
github pydata / xarray / xarray / coding / times.py View on Github external
def encode_datetime(d):
        return np.nan if d is None else cftime.date2num(d, units, calendar)