Note that there are some explanatory texts on larger screens.

plurals
  1. POPython - cPickle nested datetime objects
    primarykey
    data
    text
    <p>I have a list of lists, each sublist looking something like this:</p> <pre><code>a = [datetime.datetime(2012, 2, 1), datetime.datetime(2012, 2, 2), 'string', 4.00] b = [datetime.datetime(2012, 3, 1), datetime.datetime(2012, 3, 4), 'another_string', 5.00] list_of_lists = [a,b] </code></pre> <p>To pickle the list:</p> <pre><code>cPickle.dump(list_of_lists, open(filename, 'wb')) #filename defined </code></pre> <p>When run, it raises:</p> <pre><code>Traceback (most recent call last): File "analyze_data.py", line 129, in &lt;module&gt; analyze_data(sys.argv[1]) #because the dump runs inside a function File "analyze_data.py", line 77, in analyze_data cPickle.dump(list_of_lists, open(filename, 'wb')) TypeError: 'datetime.datetime' object is not callable </code></pre> <p>I've replicated the error on Python 2.7.3 and 2.6.8.</p> <p>Same error/traceback with regular pickle as well. Also, print statements immediately before the cPickle.dump suggest the error occurs here and not somewhere else.</p> <p>From the <a href="http://docs.python.org/2/library/pickle.html" rel="nofollow">docs</a>, it sounds like you can cPickle nested objects, not all of which must be built-in types. Perhaps I could change all the <a href="http://docs.python.org/2/library/datetime.html" rel="nofollow">datetime</a> objects to strings. No doubt there are many ways to accomplish serializing and I could adjust the code to make the above a non-issue. However, I need to understand why it's not possible, if that indeed is the case.</p> <p>Can anyone explain why nested datetime objects are not serializable via cPickle/pickle? </p> <p>EDIT: Pickling the above data structure works fine outside a function. Inside, no dice. See below.</p> <pre><code>def analyze_data(some_id, some_date=default_date): #some_id/some_date (datetime object) defined above … #create list_of_lists … string_date = some_date.strftime('%Y%m%d') #works filename = '{0}_{1}.p'.format(some_id, string_date) #filename created fine cPickle.dump(list_of_lists, open(filename, 'wb')) #kaboom </code></pre> <p>I map this function to other data in other modules, so ideally would like to keep the pickling inside a function call. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload