简体   繁体   中英

Netcdf dataset conversion from seconds from starting time to utc hours

I am working with a netcdf format code and I need to convert the time from seconds from the starting time (2016-01-01 00:00:00.0) to time in UTC. I'm fairly new to all of this so I am really struggling!

I have tried using the num2date from netCDF4 .

from netCDF4 import date2num , num2date, Dataset
time=f.variables['time'][:]
dates=netCDF4.num2date(time[:],time.units)
print(dates.strftime('%Y%m%d%H') for date in dates)

AttributeError: 'MaskedArray' object has no attribute 'units'

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 , eg

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 eg 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM