I want to store a list of datetimes in a binary file in Python.
EDIT: by \"binary\" I mean the best digital representation for each datatype. The application for thi
If you want to save an object to a binary file, you may think about pickle
As far as I know, it writes a byte stream, so it's binary enough, but the result is
Python-specific
Also, I think it should work with datetime.
And you'll have this for saving:
with open('your_file', 'wb') as file:
pickle.Pickler(file).dump(your_var)
And this for recovering
with open('your_file', 'rb') as file:
recovered=pickle.Unpickler(file).load()
I have found a way using the Unix timestamp and storing it as an integer. This works for me because I don't need a subsecond resolution, but I think long integers would allow for microsecond resolution with some modifications of the code.
The changes from my original consist in replacing calendar.timegm
by time.mktime
and also utctimetuple
by timetuple
, to keep everything naive.
This:
import datetime
import struct
import time
now = datetime.datetime.now()
print now
stamp = time.mktime(now.timetuple())
print stamp
recoverstamp = datetime.datetime.fromtimestamp(stamp)
print recoverstamp
binarydatetime = struct.pack('<L', stamp)
recoverbinstamp = struct.unpack('<L', binarydatetime)[0]
print recoverbinstamp
recovernow = datetime.datetime.fromtimestamp(recoverbinstamp)
print recovernow
Returns this:
2013-09-02 11:06:28.064000
1378130788.0
2013-09-02 11:06:28
1378130788
2013-09-02 11:06:28
From this, I can easily write the packed binarydatetime
to file, and read it back later.
By far the most simple solution is to use Temporenc: http://temporenc.readthedocs.org/
It takes care of all the encoding/decoding and allows you to write a Python datetime object to a file:
now = datetime.datetime.now()
temporenc.pack(fp, now)
To read it back, this suffices:
dt = temporenc.unpack(fp)
print(dt)