Write and read Datetime to binary format in Python

前端 未结 3 874
春和景丽
春和景丽 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: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('

    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.

提交回复
热议问题