Search code examples
pythonpython-2.6packunpack

How to unpack binary formatted dates in python?


In a database export file i have a column with dates which are stored in binary format. I'm trying to unpack dates in the file so that "\x07\xdb\x0c\x01" becomes "01-12-2011" again.

I know how the hexadecimal values corresspond to their decimal counterpart,

0x07DB = 2011
0x0C = 12
0x01 = 01

But how to properly unpack these formatted dates?


Solution

  • Use the struct module to unpack these values to a tuple of integers:

    import struct
    year, month, day = struct.unpack('>HBB', "\x07\xdb\x0c\x01")
    

    The >HBB format specifier tells struct to expect 3 values in little endian format, one unsigned short (a 2 byte value, read as an integer) and to unsigned chars (1 byte values, read as integers).

    You could then pass these to datetime.date() to create a date object if you want:

    from datetime import date
    import struct
    
    somedate = date(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))
    

    Demo:

    >>> import struct
    >>> from datetime import date
    >>> date(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))
    datetime.date(2011, 12, 1)
    

    or you could use string formatting:

    >>> '{2:02d}-{1:02d}-{0}'.format(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))
    '01-12-2011'
    

    to create a string representing that date.