Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Epoch DateTime to Byte Array in Python

Tags:

python

epoch

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

like image 204
atulthree Avatar asked Feb 23 '26 21:02

atulthree


1 Answers

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

like image 90
trs Avatar answered Feb 25 '26 10:02

trs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!