I'd like to serialize a Date in python to a URL Safe string.
I remember in C++, I used to just take the integer representing the number of seconds since January 1st 1970 (or something like that). Then I could turn it into a Base64 url-safe string. C++ dates were designed to be able to pass these integers around easily.
Ideally in Python, I'd like to get a byte array representing the date, then pass that to base64.urlsafe_b64encode(). Then when I wanted to de-serialize, I could de-encode the bytes and pass it back into a datetime object. I do not see how to do this in Python though.
I believe I could use datetime.isoformat(), but the string produced by that seems to be unnecessarily long and I do not need it to be human readable. I could also write custom functions to do the translation, but I'd like to use official library code if possible.
Am I missing something? is there an "easy" way to do this that I am not seeing?
Thanks!
Edit:
Alright, so this is what I settled on. It is a variant of what @bgporter suggested below. My goal was to turn the datetime information into a url-safe string without taking up too much unnecessary space so I modified the code such that the bytes from the "int" timestamp are being directly base64 url-encoded as opposed to translated into a string of digits (which don't need to be base64 url-encoded). The resulting timestamp is about 8 characters and looks like this: a7NaTw==:
Encode timestamp (url-safe Base64 string):
url_safe_timestamp = base64.urlsafe_b64encode(struct.pack('L', int(time.time())))
Decode timestamp (Date object):
decoded_timestamp = datetime.datetime.fromtimestamp(float(struct.unpack('L', base64.urlsafe_b64decode(url_safe_timestamp))[0]))
You mean like this:
>>> import base64
>>> import time
>>> encoded = base64.urlsafe_b64encode("%d" % int(time.time()))
>>> print encoded
'MTMzMTMyOTE5NA=='
>>> decoded = int(base64.urlsafe_b64decode(encoded))
>>> print decoded
1331329194
>>> import datetime
>>> datetime.datetime.fromtimestamp(decoded)
datetime.datetime(2012, 3, 9, 16, 39, 54)
?
(and I'm not sure why base 64 encoding here is better than just using a hex value -- what am I missing?)
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