Convert time decimal to datetime object python
<p>I am trying to convert a decimal time to a datetime object to look for the months in order to later divide the time into seasons. I did some research and stumbled upon datetime.datetime.fromtimestamp but everything I have tried produces the following error:</p>

<pre><code>                 TypeError: 'datetime.datetime' object is not iterable
</code></pre>

<p>In the past, I have used pandas to create a new time array, but do not feel that is best for my given situation. Currently I have the following in my code and tried doing it without the for loop as well, in hopes that I can get fromtimestamp() to work correctly.</p>

<pre><code>raw_time = (data.variables['time'].getValue()/float(365*24))+1800 #hours since 1800
time = n.where((raw_time&gt;=2006)&amp;(time&lt;=2016)) #our specific time interval

annual_time = []
for i in raw_time[time]:
    annual_time.extend(datetime.datetime.fromtimestamp(i))
</code></pre>

<p>My time was read in from as netCDF file and currently appears as follows:</p>

<pre><code>print raw_time[time]
array([ 2006.05205479,  2006.1369863 ,  2006.22191781,  2006.29863014,
    2006.38356164,  2006.46575342,  2006.55068493,  2006.63287671,
    2006.71780822,  2006.80273973,  2006.88493151,  2006.96986301,
    2007.05205479,  2007.1369863 ,  2007.22191781,  2007.29863014,
    2007.38356164,  2007.46575342,  2007.55068493,  2007.63287671,
    2007.71780822,  2007.80273973,  2007.88493151,  2007.96986301,
    2008.05205479,  2008.1369863 ,  2008.22191781,  2008.30136986,
    2008.38630137,  2008.46849315,  2008.55342466,  2008.63561644,
    2008.72054795,  2008.80547945,  2008.88767123,  2008.97260274, ...])
</code></pre>

<p>You should use <a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF4 num2date</a> to convert <code>time</code> from numeric values to datetime objects. </p>

<pre><code>import netCDF4

ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet 
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
</code></pre>

<p>This will create a <code>time_convert</code> array of datetime objects that you can then work with to generate seasons, for example. </p>

python datetime