I have an xarray.Dataset
, ds, with a time variable that is:
array([cftime.DatetimeGregorian(2021, 10, 16, 9, 50, 1, 0)], dtype=object)
I would like to use the date in the plot title, as:
fig = plt.figure()
ax = plt.axes(projection = ccrs.PlateCarree(central_longitude=200)) # Orthographic
day_str = np.datetime_as_string(ds.time, unit='D').tobytes().decode()
ax.set_title(day_str, size = 10.)
The problem I'm having is that, when I use the variable day_str
in the title it is all garbled.
type(day_str)
returns str
. When I type print(day_str)
, I get: 2021-10-16
,
as expected. So, I do not think this is a cftime to python datetime issue. What am I missing?
Another thing that is relevant is that evaluating 'foo' day_str
, gives:
'foo2\x00\x00\x000\x00\x00\x002\x00\x00\x001\x00\x00\x00-\x00\x00\x001\x00\x00\x000\x00\x00\x00-\x00\x00\x001\x00\x00\x006\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
EDIT: Well, this isn't very elegant, but it works:
fig = plt.figure()
ax = plt.axes(projection = ccrs.PlateCarree(central_longitude=200)) # Orthographic
daystr=ds.time.dt.day.astype(str).values[0]
monstr=ds.time.dt.month.astype(str).values[0]
yrstr=ds.time.dt.year.astype(str).values[0]
day_str = monstr '-' daystr '-' yrstr
ax.set_title('SST, ' day_str, size = 10.)
CodePudding user response:
As far as I interpret your question, this is what I get when I convert your DatetimeGregorian
objet to a string:
import cftime
str(cftime.DatetimeGregorian(2021, 10, 16, 9, 50, 1, 0))
Resulting string:
'2021-10-16 09:50:01'
CodePudding user response:
The section on time series in the xarray documentation is a good resource: http://xarray.pydata.org/en/stable/user-guide/time-series.html
A good way to handle this would be to use the using the special .dt
accessor with the method .strftime
:
day_str = ds.time.isel(time=-1).dt.strftime("%a, %b %d %H:%M").values
or, equivalently in this case,
day_str=ds.time.dt.strftime("%a, %b %d %H:%M").values[0]
With this approach, 'SST, ' day_str
gives
'SST, Tue, Oct 19 09:50'