jay
jay

Reputation: 1463

Converting 'cftime._cftime.DatetimeGregorian' to a float while using matplotlib

I am working with netcdf4 package while analyzing climate data from CRU. I was able to get a time series plot for monthly temp. variation in city of Kabul from 2011 thru 2019.

fig = plt.figure(figsize=(12,4))
ax = fig.add_subplot(111)
plt.plot(time,global_average)
ax.set_xlabel('Time(in days since Jan 1,1901)')
ax.set_ylabel('Monthly Temperature')
ax.set_title('Variation of Monthly Temperature in Kabul City')
plt.show()

Here the time variable is number of days since Jan 1,1900.

enter image description here

But I am trying to add the time axis as values like ' 01-01-2011', 02-01-2012' and so on. I tried to convert the time dimension into cftime.DatetimeGregorian using the following function;

t = netCDF4.num2date(temp_data_2011_2019.variables['time'][:],temp_data_2011_2019.variables['time'].units,\
                     temp_data_2011_2019.variables['time'].calendar)

This works and gives me a masked array. But when put this argument np.ma.getdata(t) in the plot command, get the error

TypeError: float() argument must be a string or a number, not 'cftime._cftime.DatetimeGregorian'

can use an alternative way to get the dates in desired format in the line plot?

Upvotes: 1

Views: 1048

Answers (2)

If you have an array of cftime.DatetimeGregorian timestamp you can convert it into a list of string using the following code:

import cftime

time_gregorian = np.array([
       cftime.DatetimeGregorian(2013, 6, 1, 0, 30, 0, 0, has_year_zero=False),
       cftime.DatetimeGregorian(2013, 6, 1, 1, 30, 0, 0, has_year_zero=False),
       cftime.DatetimeGregorian(2013, 6, 1, 2, 30, 0, 0, has_year_zero=False)])

time_string = list(map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'),time_gregorian))

print(time_string)

Output

['2013-06-01 00:30:00', '2013-06-01 01:30:00', '2013-06-01 02:30:00']

Thus, you can format the string timestamp as you wish.

Upvotes: 0

mozway
mozway

Reputation: 262254

I don't know cftime, but why not use pd.to_datetime to do your conversion?

example input:

df = pd.DataFrame({'date': ['Jan 1, 1900', 'Aug 8, 2021']})
          date
0  Jan 1, 1900
1  Aug 8, 2021

conversion:

pd.to_datetime(df['date'], format='%b %d, %Y')

output:

0   1900-01-01
1   2021-08-08
Name: date, dtype: datetime64[ns]

And if you want to get strings with the DD-MM-YYYY format:

pd.to_datetime(df['date'], format='%b %d, %Y').dt.strftime('%d-%m-%Y')

output:

0    01-01-1900
1    08-08-2021
Name: date, dtype: object

Upvotes: 1

Related Questions