import calendar
import time


def toutctimestamp(stamp):
    """ Converts a naive datetime object to a UTC unix timestamp. This has an
        advantage over `time.mktime` in that it preserves the decimal portion
        of the timestamp when converting.

        :param datetime stamp: Datetime to convert
        :returns: Unix timestamp as a ``float``

        ::

            from datetime import datetime
            from pytool.time import toutctimestamp

            utc_stamp = toutctimestamp(datetime.now())

    """
    decimal = (1.0 * stamp.microsecond / 10**6)
    if stamp.tzinfo:
        # Hooray, it's timezone aware, we are saved!
        return calendar.timegm(stamp.utctimetuple()) + decimal

    # We don't have a timezone... shit
    return time.mktime(stamp.timetuple()) + decimal