3

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.

D.L
  • 4,339
  • 5
  • 22
  • 45
  • what problem are you are you trying to solve here? converting datetime to a numeric representation that is smaller than the string representation? – FObersteiner Apr 16 '21 at 12:40

2 Answers2

1

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
D.L
  • 4,339
  • 5
  • 22
  • 45
1

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.

evandrix
  • 6,041
  • 4
  • 27
  • 38
FObersteiner
  • 22,500
  • 8
  • 42
  • 72