Boandlkramer Boandlkramer - 3 months ago 7x
Python Question

Are datetime timestamps updated after pickling?

I'm creating a timestamp using Later in the code, this one shall be compared to another (current) timestamp, but just on the day-level: "If the current day is not the day of the former timestamp, do stuff".

To do this, I'm saving the first timestamp using pickle. Now I wonder, if the datetime-object will be auto-updated after pickle.load, if the loading date is not the "dumping" date. After all, the function is named "today"... I hope, this is not a stupid question and I managed to explain my issue properly.


The method creates a new datetime.datetime object of the current moment. The object itself doesn't know how it was created, i.e. neither the function nor the function's intention. It only know when it was created, and this is what will be stored.

If you look at the documentation of the function (e.g. via help(, it provides this:

Current date or datetime: same as self.__class__.fromtimestamp(time.time())

Now, time.time() provides the current timestamp, e.g. 1468585949.653488. This is a plain number (float or int), which is constant once created. This number is then simply fed to datetime.datetime.fromtimestamp. For any given timestamp, this will always give you the same datetime [1].

In [12]: datetime.datetime.fromtimestamp(1468585949.653488)
Out[12]: datetime.datetime(2016, 7, 15, 14, 32, 29, 653487)

If you dump this object, you get a regular datetime.datetime object. It's just the plain class datetime.datetime and its data, no function or method reference such as

In [3]: print(pickle.dumps(datetime.datetime.fromtimestamp(1468585949.653488),protocol=0))
# cdatetime  # class datetime.\
# datetime   #                datetime
# p0         # push last object (datetime.datetime) to stack as p0
# (S'\x07\xe0\x07\x0f\x0e \x1d\t\xf8\xb0'  # group '(' start, string 'S' from binary ('\x07...')
# p1         # push last object (string) to stack as p1
# tp2        # create tuple from last stack group, push to stack as p2
# Rp3        # call p0(*p2)
# .          # done

So, what does this piece of junk do? It looks up the object datetime.datetime as p0, stores the string '\x07\xe0\x07\x0f\x0e \x1d\t\xf8\xb0' as p1, creates the tuple p2 = tuple((p1,)), then calls p0(*p2).

Or in other words, datetime.datetime('\x07\xe0\x07\x0f\x0e \x1d\t\xf8\xb0') is returned. Note that the argument to datetime.datetime is a constant string. This will always give you the original datetime:

In [30]: datetime.datetime('\x07\xe0\x07\x0f\x0e \x1d\t\xf8\xb0')
Out[30]: datetime.datetime(2016, 7, 15, 14, 32, 29, 653488)

[1] Baring differences in timezones etc.