URL-Safe Timestamps using Base64

Passing around timestamps in URLs is a common task. We usually want our URLs to be as shortest as possible. I’ve found using Base64 to result in the shortest URL-safe representation, just 6 chars. This compares with the 12 chars of the naive way, and 8 chars when using hex representation.

The following Python functions allow you to build and read these 6 chars URL-safe timestamps:

import base64
import struct
import time

def build_timestamp():
    Return a 6 chars url-safe timestamp
    return base64.urlsafe_b64encode(struct.pack("!L",int(time.time())))[:-2]

def read_timestamp(t):
    Convert a 6 chars url-safe timestamp back to time
    return struct.unpack("!L",base64.urlsafe_b64decode(t+"=="))[0]

These functions work by translating the timestamp into a 4-byte binary form and then encoding it using a URL-safe version of Base64. And finally we strip the padding, which is neither URL-safe nor necessary (as we know the size of the encoded data).

The result looks something like this:

In [72]: build_timestamp()
Out[72]: 'S9sNOQ'

We got a timestamp in using only 6 URL-safe chars.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.