Home > other >  How to format dates with a Xarray GRIB file
How to format dates with a Xarray GRIB file

Time:03-21

I have a grib file and I am trying to format the date for my title, but I don't know the best way to accomplish this. The date format in the dataset is 1970-01-01. I would like it to display in the title as 01-01-1970. I get the following error when I run the code, "'str' object has no attribute 'strftime'.

ds=xr.open_dataset('./Data/ecmwf_dataset/1month_anomaly_Global_ea_2t_197901_1981-2010_v02.grib',
                   engine='cfgrib',backend_kwargs={'indexpath': ''})

time = ds['time']
time = np.datetime_as_string(time, unit='D')
time.astype(datetime.datetime).strftime('%m-d-%Y')

ax.set_title('Arctic 2-m Temperature Anomaly: '   time)

enter image description here enter image description here

CodePudding user response:

Try using .dt.strftime:

time = time.astype(datetime.datetime).dt.strftime('%m-%d-%Y')

CodePudding user response:

Got it to work after upgrading xarray to version 0.20.1, rearranging my code, and rerunning. This is the final code to create the time variable and use it in a title:

time = ds['time'].dt.strftime('%m-%d-%Y')
ax.set_title('Arctic 2-m Temperature Anomaly: \n'   time.values, size=fontsize, weight='bold')
  • Related