Skip to content

Back and forth conversions fail with num2date and date2num #187

@mcuntz

Description

@mcuntz

I have problems going back and forth with the num2date and date2num routines.

One problem is a millisecond problem:

import cftime as cf
import datetime as dt
dt1 = dt.datetime(1810, 4, 24, 16, 15, 10)
cf.num2date(cf.date2num(dt1, units='days since -4713-01-01 12:00'), units='days since -4713-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 9, 999999)
cf.num2date(cf.date2num(dt1, units='days since 0001-01-01 12:00'), units='days since 0001-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 9, 999999)
cf.num2date(cf.date2num(dt1, units='days since 1600-01-01 12:00'), units='days since 1600-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 9, 999999)
cf.num2date(cf.date2num(dt1, units='days since 1700-01-01 12:00'), units='days since 1700-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 10, 0)

The other one is off by one week if I use Lotus dates (or Excel 1904 dates):

dt2 = dt.datetime(1271, 3, 18, 19, 41, 34)
cf.num2date(cf.date2num(dt2, units='days since 1904-01-01 00:00'), units='days since 1904-01-01 00:00')
-> Out: cftime.DatetimeGregorian(1271, 3, 11, 19, 41, 34, 0)

I am the one who did the pull request once: Unidata/netcdf4-python#433, adding a little offset corresponding to about 45 milliseconds. So I if do the same here, I get the right seconds but not the right microseconds, of course:

import numpy as np
eps = np.finfo(np.float).eps
dt1 = dt.datetime(1810, 4, 24, 16, 15, 10)
j1 = cf.date2num(dt1, units='days since 0001-01-01 12:00')
cf.num2date(j1, units='days since 0001-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 9, 999999)
j1 += np.abs(j1) * eps
cf.num2date(j1, units='days since 0001-01-01 12:00')
-> Out: cftime.DatetimeGregorian(1810, 4, 24, 16, 15, 10, 9)

Perhaps you could introduce the rounding of microseconds again, just as you did for issue #78.
I have no idea about the missing week though.

I use cftime version 1.2.0 on Python 3.8.3 on macOS 10.15.5.

Kind regards
Matthias

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions