[SciPy-User] Pickling timeseries Dates

Robert Ferrell ferrell@diablotech....
Wed Dec 16 15:45:31 CST 2009


On Dec 10, 2009, at 9:28 PM, David Baddeley wrote:

> It also shouldn't be to hard to register a new pickle handler that  
> takes care of the conversion to e.g. datetime for you. I'm not  
> familiar with timeseries stuff, but wrote something similar to let  
> me pickle slices, which I've included below - as you can see it's  
> pretty trivial. After that you can carry on treating your date  
> (slice) objects as though they were picklable.
>
> import copy_reg
>
> def pickleSlice(slice):
>        return unpickleSlice, (slice.start, slice.stop, slice.step)
>
> def unpickleSlice(start, stop, step):
>        return slice(start, stop, step)
>
> copy_reg.pickle(slice, pickleSlice, unpickleSlice)
>
> best wishes,
> David
>

That was a great suggestion.  Seems to work for me.  If I import this  
at the top of my package (or as soon as I can) will it be available  
whenever I need it?

In case anybody else needs to pickle Dates, here's the code that seems  
to work for me.

= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
= 
========================================================================
# Attempt to pickle timeseries date instances.
# This converts a ts.Date instance to a string
# Frequency is lost, but I'm only using 'd', so that's okay for me.

import pickle
import copy_reg
import scikits.timeseries as ts

def pickleDT(dt):
	"""Pickle __reduce__ method for a date instance dt by converting to a  
string, then pickling."""
	dA = str(dt)
	ds = pickle.dumps(dA)
	# This is what __reduce__ is supposed to return
	return unpickleDT, (ds,)
	
def unpickleDT(dA):
	"""Unpickle a date instance with frequency 'd'."""
	ds = pickle.loads(dA)
	dt = ts.Date('d', ds)
	return dt

# Register these methods
copy_reg.pickle(ts.Date, pickleDT, unpickleDT)

if __name__ == '__main__':
	sD = ts.Date('d', '2009-11-30')
	ds = pickle.dumps(sD)
	dt = pickle.loads(ds)
	print 'Started with %s, unpickled %s.' % (sD, dt)
	if dt == sD:
		print 'Yeah, flawless victory!'
	else:
		print 'Boo, shameful failure.'



More information about the SciPy-User mailing list