我有一个xarray.Dataset
,ds,带有一个时间变量,它是:
array([cftime.DatetimeGregorian(2021, 10, 16, 9, 50, 1, 0)], dtype=object)
我想使用地块标题中的日期,如下所示:
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.)
我遇到的问题是,当我在标题中使用变量day_str
时,它都是乱码
type(day_str)
返回str
。当我键入print(day_str)
时,我得到:2021-10-16
,
正如所料。因此,我不认为这是一个cftime到python日期时间的问题。我错过了什么
另一件相关的事情是,评估'foo' + day_str
,给出:
'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'
编辑: 嗯,这不是很优雅,但很有效:
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.)
xarray文档中关于时间序列的部分是一个很好的资源: http://xarray.pydata.org/en/stable/user-guide/time-series.html
处理此问题的一个好方法是将特殊的
.dt
访问器与方法.strftime
一起使用:或者,在这种情况下
通过这种方法,
'SST, ' + day_str
给出就我对你的问题的理解而言,当我将你的
DatetimeGregorian
对象转换为字符串时,我得到的是:结果字符串:
相关问题 更多 >
编程相关推荐