Write and read Datetime to binary format in Python

前端 未结 3 875
春和景丽
春和景丽 2021-01-03 06:10

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

相关标签:
3条回答
  • 2021-01-03 06:50

    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()
    
    0 讨论(0)
  • 2021-01-03 06:59

    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.

    0 讨论(0)
  • 2021-01-03 07:00

    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)
    
    0 讨论(0)
提交回复
热议问题