from datetime import datetime
import pytz


def _datetime_from_query(ts):
    """Converts the above arbitrary format back to a datetime object, complete
    with a time zone.  `ts` should be a string, straight out of the query.

    Returns None if `ts` is missing or junk.
    """
    if not ts:
        return None

    # Avoid using float() on the way back in, too
    if u'.' in ts:
        seconds, microseconds = ts.split('.', 1)
        # Pad to six digits
        microseconds = (microseconds + u'000000')[0:6]
    else:
        seconds = ts
        microseconds = 0

    try:
        dt = datetime.fromtimestamp(int(seconds), pytz.utc)
        dt = dt.replace(microsecond=int(microseconds))
        return dt
    except TypeError:
        # Nothing reasonable to do, since this is supposed to be a value just
        # for us.  If someone has been dicking with it...  ignore it
        return None