Hello, I'm trying to write out a variable with a datetime64 time axis to netcdf and xarray seems to automatically write it out in the units of "hours since whenever". I'm trying to read this in to the CESM SST time diddling code which only seems to work if the time axis is in units of "days since whenever". Does anyone know how I can force xarray to write out the time axis to the netcdf in this format? I have tried ensuring that the time axis only consists of days, but it still writes it out in hours since. I could manually make the time axis and give it those attributes, but I'm wondering if there's a better way. Thanks for any help.
@Isla Simpson: Can you share the first few elements of the time
coordinate?
Isla, please try
ds.time.encoding["units"] = "days since whenever"
prior to writing the Dataset out, where ds
is the xarray Dataset being written out.
This tells xarray what units to use for time when it writes it out, instead of letting xarray decide for you.
Or, if you are writing the netcdf files using Xarray's to_netcdf
method, you can include the encoding
in the to_netcdf
function directly:
ds.to_netcdf('my_netcdf_file.nc', encoding={'time': {'units': 'days since whenever'}})
super. Problem solved, thank you both! I also realized that when I'd tried to make the time not have any hours, it was getting overwritten as I was merging the variable in with another one which still had the original time axis. But it's good to know how to do this using these ways that are more straightforward. Thank you!
The documentation on this topic is here
Ah, thank you. I had just been looking on the "to_netcdf" documentation page.
Code in question:
plat,plon = 69 , (360.-149.37) # °N, °W
plotVar = maxALT.isel(year=slice(-10,None)).mean(['ens','year'])
plt.figure(figsize=(8,6), dpi= 90)
# Make a new projection, time of class "NorthPolarStereo"
ax = plt.axes(projection=ccrs.NorthPolarStereo(true_scale_latitude=70))
# here is here you tell Cartopy that the projection
# of your 'x' and 'y' are geographic (lons and lats)
# and that you want to transform those lats and lons
#into 'x' and 'y' in the projection
plt.pcolormesh(maxALT.lon, maxALT.lat, plotVar,
transform=ccrs.PlateCarree());
# plot land
ax.add_feature(cfeature.OCEAN)
ax.gridlines()
ax.coastlines()
plt.colorbar(label='m')
plt.title('Active Layer Thickness')
# Limit the map to -60 degrees latitude and below.
ax.set_extent([-180, 180, 90, 60], ccrs.PlateCarree())
# Compute a circle in axes coordinates, which we can use as a boundary
# for the map. We can pan/zoom as much as we like - the boundary will be
# permanently circular.
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
#circle = mpath.Path(verts * radius + center)
plt.plot(plon, plat, markersize=4,
color='red', linewidth=0, marker='o',
transform=ccrs.Geodetic(),
)
#ax.set_boundary(circle, transform=ax.transAxes)
print(np.round(plotVar.sel(lat=plat,lon=plon,method='nearest').values,2))
That's just a warning about Cartopy using something that's been deprecated by the latest Shapely. It should be fixed by the Cartopy 0.20.2 release. So you can either update cartopy or safely ignore the warning.
Last updated: May 16 2025 at 17:14 UTC