在NetCDF文件中写入时间

时间:2016-10-12 11:21:52

标签: python netcdf

在netCDF文件中使用NETCDF4程序包写入时间。

dates = []
for iday in range(84):
    dates.append(datetime.datetime(2016, 10, 1) + atetime.timedelta(hours = iday))
times[:] = date2num(dates, units=times.units, calendar = imes.calendar)
# print times[:]
for ii, i in enumerate(times[:]):
    print i, num2date(i, units=times.units), dates[ii]

时代紧迫:

17669815.0 2016-10-04 07:00:00 2016-10-04 07:00:00
17669816.0 2016-10-04 08:00:00.000006 2016-10-04 08:00:00
17669817.0 2016-10-04 09:00:00 2016-10-04 09:00:00
17669818.0 2016-10-04 10:00:00 2016-10-04 10:00:00
17669819.0 2016-10-04 11:00:00.000006 2016-10-04 11:00:00

但在阅读netcdf文件时:

input_file = '/home/lovechang/test.nc'
data = Dataset(input_file)

times = data.variables['time']
# print times[:]
# print num2date(times[:], units=times.units)
for i in times[:]:
    print i, num2date(i, units=times.units)

结果:

17669813.0 2016-10-04 05:00:00.000006
17669814.0 2016-10-04 06:00:00
17669815.0 2016-10-04 07:00:00
17669816.0 2016-10-04 08:00:00.000006
17669817.0 2016-10-04 09:00:00
17669818.0 2016-10-04 10:00:00
17669819.0 2016-10-04 11:00:00.000006

Ncview显示时间不是准时。

screenshot of Ncview program running

那么时代发生了什么? 如何在netcdf文件中准时写入小时?

1 个答案:

答案 0 :(得分:3)

根据您选择的时间单位和数据类型,您可能会遇到浮点精度问题。例如,如果您在days since 1970-01-01 00:00中指定时间,则32位浮点数不足,您应该使用64位浮点数:

import datetime
import netCDF4

times = [datetime.datetime(2016, 10, 1) + datetime.timedelta(hours=hour)
         for hour in range(84)]

# Create netCDF file
calendar = 'standard'
units = 'days since 1970-01-01 00:00'
ds = netCDF4.Dataset('test.nc', 'w')
timedim = ds.createDimension(dimname='time', size=len(times))

# Write timestamps to netCDF file using 32bit float
timevar32 = ds.createVariable(varname='time32', dimensions=('time',),
                              datatype='float32')
timevar32[:] = netCDF4.date2num(times, units=units, calendar=calendar)

# Write timestamps to netCDF file using 64bit float
timevar64 = ds.createVariable(varname='time64', dimensions=('time',),
                              datatype='float64')
timevar64[:] = netCDF4.date2num(times, units=units, calendar=calendar)

# Read timestamps from netCDF file
times32 = netCDF4.num2date(timevar32[:], units=units, calendar=calendar)
times64 = netCDF4.num2date(timevar64[:], units=units, calendar=calendar)
for time, time32, time64 in zip(times, times32, times64):
    print "original  ", time
    print "  32 bit  ", time32
    print "  64 bit  ", time64
    print

如果您在hours since 2016-10-01 00:00中指定了时间,即使是整数就足够了(在本例中)。