Skip to content

Instantly share code, notes, and snippets.

@lukegre
Last active April 17, 2017 10:59
Show Gist options
  • Save lukegre/7ff192ba7ef97922bcfd to your computer and use it in GitHub Desktop.
Save lukegre/7ff192ba7ef97922bcfd to your computer and use it in GitHub Desktop.
This class takes the tm_* attributes from a timetuple and applies them to a numpy.ndarray. Also includes datestr and datetime functions.
import numpy as np
from pylab import num2date
from itertools import ifilter
from time import struct_time
from __future__ import print_function
class TimeTupleArray(np.ndarray):
def __new__(cls, input_array, info=None):
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
# add the new attribute to the created instance
tm_attr = lambda s: s.startswith('tm')
for tm in ifilter(tm_attr, dir(struct_time)):
setattr(obj, tm, cls._get_timetuple_output(obj, tm))
# Finally, we must return the newly created object:
return obj
def __array_finalize__(self, obj):
# see InfoArray.__array_finalize__ for comments
if obj is None: return
self.info = getattr(obj, 'info', None)
def _get_timetuple_output(self, tm_str):
out = [getattr(d.timetuple(), tm_str) for d in self._datetime]
return np.array(out).squeeze()
@property
def _datetime(self):
return np.array(num2date(self))
def datetime(self):
return self._datetime.squeeze()
def datestr(self, fmt='%Y-%m-%d'):
out = [d.strftime(fmt) for d in self._datetime]
return np.array(out).squeeze()
@property
def timetuple(self):
out = [d.timetuple() for d in self._datetime]
return np.array(out).squeeze()
if __name__ == "__main__":
test = TimeTupleArray([734412])
print ('YEAR: ', test.tm_year)
print ('MONTH:', test.tm_mon)
print ('JDAY: ', test.tm_yday)
print ('TUPLE:', test.timetuple)
print ('STR: ', test.datestr())
print ('DATE: ', test.datetime())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment