gpt4 book ai didi

python - NetCDF 文件中的写入时间

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:53 25 4
gpt4 key购买 nike

在 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 文件中准时写入小时数?

最佳答案

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

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

如果您指定自 2016 年 10 月 1 日 00:00 以来的 小时数 时间,即使是整数也足够(在此示例中)。

关于python - NetCDF 文件中的写入时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com