Search code examples
python-3.xnetcdf4

How fix the error "ValueError: Julian Day must be positive" in netCDF4.num2date?


Here is the partial code:

import netCDF4
import pandas as pd
import matplotlib.pyplot as plt

file='/Users/dedeco/Downloads/_grib2netcdf-atls12-95e2cf679cd58ee9b4db4dd119a05a8d-OzkfHp.nc'
nc = netCDF4.Dataset(file)
nc.variables.keys()

lat = nc.variables['latitude'][:]
lon = nc.variables['longitude'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)

The file can be download in the link: https://stream.ecmwf.int/data/atls12/data/data01/scratch/84/bc/_grib2netcdf-atls12-95e2cf679cd58ee9b4db4dd119a05a8d-OzkfHp.nc

So, I got this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-47-3647c36af24c> in <module>()
      2 lon = nc.variables['longitude'][:]
      3 time_var = nc.variables['time']
----> 4 dtime = netCDF4.num2date(time_var[:],time_var.units)

cftime/_cftime.pyx in cftime._cftime.num2date()

cftime/_cftime.pyx in cftime._cftime.utime.num2date()

cftime/_cftime.pyx in cftime._cftime.DateFromJulianDay()

ValueError: Julian Day must be positive

How I can fix? Any ideas?


Solution

  • I fixed the problem set the parameter (the default is standard): calendar: describes the calendar used in the time calculations.

    So replace this:

    dtime = netCDF4.num2date(time_var[:],time_var.units)
    

    by (in this case the year has 365 days):

    dtime = netCDF4.num2date(time_var[:],time_var.units,'365_day')
    

    Here is the documentation as follow:

    def date2num(

    ...)

    date2num(dates,units,calendar='standard')

    Return numeric time values given datetime objects. The units of the numeric time values are described by the units argument and the calendar keyword. The datetime objects must be in UTC with no time-zone offset. If there is a time-zone offset in units, it will be applied to the returned numeric values.

    dates: A datetime object or a sequence of datetime objects. The datetime objects should not include a time-zone offset.

    units: a string of the form since describing the time units. can be days, hours, minutes, seconds, milliseconds or microseconds. is the time origin.

    calendar: describes the calendar used in the time calculations. All the values currently defined in the CF metadata convention Valid calendars 'standard', 'gregorian', 'proleptic_gregorian' 'noleap', '365_day', '360_day', 'julian', 'all_leap', '366_day'. Default is 'standard', which is a mixed Julian/Gregorian calendar.

    returns a numeric time value, or an array of numeric time values with approximately millisecond accuracy.

    A complementar understand about the conversion can be found here.