import time


def w3c_date(i):
    """Return a valid W3C datetime given milliseconds since the epoch """
    # This function from: https://gist.github.com/mnot/246088
    year, month, day, hour, minute, second, wday, jday, dst = \
        time.gmtime(i)
    o = str(year)
    if (month, day, hour, minute, second) == (1, 1, 0, 0, 0): return o
    o = o + '-%2.2d' % month
    if (day, hour, minute, second) == (1, 0, 0, 0): return o
    o = o + '-%2.2d' % day
    if (hour, minute, second) == (0, 0, 0): return o
    o = o + 'T%2.2d:%2.2d' % (hour, minute)
    if second != 0:
        o = o + ':%2.2d' % second
    o = o + 'Z'
    
    return o