Since you extract time
from the variables in time=f.variables['time'][:]
, it will lose it's associated unit (time is just a masked array, as the error says).
What you have to feed to num2date()
is variables['time'].units
, e.g.
from netCDF4 import date2num, num2date, Dataset
file = ... # your nc file
with Dataset(file) as root:
time = root.variables['time'][:]
dates = num2date(time, root.variables['time'].units)
## directly get UTC hours here:
# unit_utchours = root.variables['time'].units.replace('seconds', 'hours')
## would e.g. be 'hours since 2019-08-15 00:00:00'
# utc_hours = date2num(dates, unit_utchours)
# check:
print(dates[0].strftime('%Y%m%d%H'))
# e.g. prints 2019081516
...to get the dates as a number, you could e.g. do
num_dates = [int(d.strftime('%Y%m%d%H')) for d in dates]
# replace int with float if you need floating point numbers etc.
...to get the dates in UTC hours, see the commented section in the first code block. Since the dates array contains objects of type datetime.datetime, you could also do
utc_hours = [d.hour+(d.minute/60)+(d.second/3600) for d in dates]