[SOLVED] How to format dates with a Xarray GRIB file

Issue

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

Solution

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')

Answered By – Chris Turnbull

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *