Search code examples
pythonepoch

Converting Epoch DateTime to Byte Array in Python


I am trying to convert epoch datetime to byte array in python but it is coming as 10 Byte, it should come in 4 Byte.

from time import time
curTime = int(time.time())
b = bytearray(str(curTime))
len(b)                 #comming as 10

Can any one help where i am wrong


Solution

  • You are converting the string representation of the timestamp, not the integer.

    What you need is this function:

    struct.pack_into(fmt, buffer, offset, v1, v2, ...) It's documented at http://docs.python.org/library/struct.html near the top.

    import struct
    from time import time
    curTime = int(time())
    b = struct.pack(">i", curTime)
    len(b)    # 4
    

    Stolen from here: https://stackoverflow.com/a/7921876/2442434