I have the following code:
import datetime
time_stamp = datetime.datetime.utcnow()
print(time_stamp)
This returns the following:
2021-04-16 11:06:16.867390
I would like to convert the entire timestamp, including the microseconds (ie. all 6 decimal places) to a unique hex number. How can i do this (preferably on one line if it exists) ?
Similar solutions are here: Getting a datetime in this format and converting to 4 byte hex . However, they do not include the decimal part of the utcnow() return function which in this case is important as it is expected to create a different hex for each microsecond change.
This seems to be one solution:
import datetime
time_stamp = datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
print(time_stamp)
time_stamp_hex = hex(int(time_stamp))
print(time_stamp_hex)
The result is:
20210416114300753898 # <- numeric
0x11879d26067ba17ea # <- hex
If you don't mind spending a few more bytes, using an ISO 8601 formatted string is a good choice because easy to read and clear how to interpret:
# encode datetime:
bts = bytes(dtobj.isoformat(timespec='microseconds'), 'ASCII') # 32 bytes
# decode datetime:
print(datetime.fromisoformat(bts.decode('ASCII')))
# 2020-01-01 00:00:00+00:00
You can also use Unix time instead (as in the question you linked), which needs only 8 bytes:
from datetime import datetime, timezone
import struct
dtobj = datetime(2020,1,1,tzinfo=timezone.utc)
# to seconds since the epoch / unix time (float)
ts = dtobj.timestamp()
# 64bit float to bytes
bts = struct.pack('!d', ts)
# hex repr
print(' '.join(f"x{b:02X}" for b in bts))
# x41 xD7 x82 xF8 x40 x00 x00 x00
# unpack and back to datetime obj
print(datetime.fromtimestamp(struct.unpack('!d', bts)[0], timezone.utc))
# 2020-01-01 00:00:00+00:00
Side-Note: don't use utcnow with this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With