
import time
from datetime import datetime
from calendar import timegm

###

_dt_formats = ('%Y-%m-%dT%H:%M:%S%Z',
               '%Y-%m-%dT%H:%M:%SZ',
               '%Y-%m-%dT%H:%M:%S',
               '%Y-%m-%d',
               '%c',
               '%a %b %d %H:%M:%S %Y',
               '%a, %d %b %Y %H:%M:%S')

def parse_timestamp ( ts, xfmts=None ):
    """Try to parse ts using some common formats for timestamps
    and return a datetime object if parsing was successfull.

    xmfts: list of additional formats to try.

    Built-in formats: see _dt_formats
    """
    fl = list(_dt_formats)
    if xfmts:
        fl.extend(list(xfmts))
    if ts.find('.') > 0:
        ts = ts.split('.', 1)[0]
    for fmt in fl:
        try:
            t = time.strptime(ts, fmt)
            t = timegm(t)
            try:
                dt = datetime.utcfromtimestamp(t)
                return dt
            except TypeError:
                raise TypeError, (type(t), 'should be float')
        except ValueError:
            pass
    raise ValueError, repr(ts)
#

def make_utc_timestamp ( now=None, delimiter='T', tz='Z' ):
    """Creat and return a iso8601 timestamp as string.

    If now is not None, it has to be either a datatime instance or a float.
    """
    if now is None:
        now = datetime.utcnow()
    elif isinstance(now, datetime):
        # ok
        pass
    elif type(now) == float:
        now = datetime.utcfromtimestamp(now)
    else:
        raise TypeError
    ts = now.replace(microsecond=0).isoformat(delimiter) + tz
    return ts
#

