Converts a timestamp given in "hhmmss[.ss]" ASCII text format to a
    datetime.time object
777978
def timestamp(s):
    '''
    
    '''
    ms_s = s[6:]
    ms = ms_s and int(float(ms_s) * 1000000) or 0

    t = datetime.time(
        hour=int(s[0:2]),
        minute=int(s[2:4]),
        second=int(s[4:6]),
        microsecond=ms)
    return t
158622
def str2unixtime(ts, fmt='%Y-%m-%d %H:%M:%S'):
    
    t = time.strptime(ts, fmt)
    return int(time.mktime(t))
301358
def unixtime_to_datetimestr(unixtime, timefmt='%Y/%m/%d %H:%M:%S', isutc=True):
    
    try:
        if unixtime == -1:
            return 'NA'
        if unixtime is None:
            return None
        if isutc:
            return datetime.datetime.utcfromtimestamp(unixtime).strftime(timefmt)
        else:
            return datetime.datetime.fromtimestamp(unixtime).strftime(timefmt)
    except ValueError:
        raise
1161540
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
        """"""
        return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
1290035
def human_timestamp(__timestamp: datetime.datetime) -> str:
    
    numstr = '. a two three four five six seven eight nine ten'.split()

    matches = [
        60 * 60 * 24 * 365,
        60 * 60 * 24 * 28,
        60 * 60 * 24 * 7,
        60 * 60 * 24,
        60 * 60,
        60,
        1,
    ]
    match_names = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second']

    if __timestamp.tzinfo is None:
        __timestamp = __timestamp.replace(tzinfo=datetime.timezone.utc)

    now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

    delta = int((now - __timestamp).total_seconds())
    for scale in matches:
        i = delta // scale
        if i:
            name = match_names[matches.index(scale)]
            break
    else:
        i = 0  # Too small

    if i == 0:
        result = 'right now'
    elif i == 1 and name in ('year', 'month', 'week'):
        result = 'last {}'.format(name)
    elif i == 1 and name == 'day':
        result = 'yesterday'
    elif i == 1 and name == 'hour':
        result = 'about an hour ago'
    else:
        result = 'about {} {}{} ago'.format(i if i > 10 else numstr[i], name,
                                            's' if i > 1 else '')
    return result
751963
def parse(self, s):
        
        return datetime.datetime.strptime(s, self.date_format).date()
417352
def std_datetimestr(self, datetimestr):
        
        return datetime.strftime(
                self.str2datetime(datetimestr), self.std_datetimeformat)
270646
def convert_datetimes_to_timestamps(data, datetime_attrs):
    
    if not data:
        return data

    new_data = {}
    for key, value in data.items():
        if key in datetime_attrs and isinstance(value, datetime):
            new_key = datetime_attrs[key]
            new_data[new_key] = timestamp_from_dt(value)
        else:
            new_data[key] = value

    return new_data
1117725
def asDateTime(self):
        
        text = str(self)
        if text.endswith('Z'):
            tzinfo = TimeMixIn.UTC
            text = text[:-1]

        elif '-' in text or '+' in text:
            if '+' in text:
                text, plusminus, tz = string.partition(text, '+')
            else:
                text, plusminus, tz = string.partition(text, '-')

            if self._shortTZ and len(tz) == 2:
                tz += '00'

            if len(tz) != 4:
                raise error.PyAsn1Error('malformed time zone offset %s' % tz)

            try:
                minutes = int(tz[:2]) * 60 + int(tz[2:])
                if plusminus == '-':
                    minutes *= -1

            except ValueError:
                raise error.PyAsn1Error('unknown time specification %s' % self)

            tzinfo = TimeMixIn.FixedOffset(minutes, '?')

        else:
            tzinfo = None

        if '.' in text or ',' in text:
            if '.' in text:
                text, _, ms = string.partition(text, '.')
            else:
                text, _, ms = string.partition(text, ',')

            try:
                ms = int(ms) * 1000

            except ValueError:
                raise error.PyAsn1Error('bad sub-second time specification %s' % self)

        else:
            ms = 0

        if self._optionalMinutes and len(text) - self._yearsDigits == 6:
            text += '0000'
        elif len(text) - self._yearsDigits == 8:
            text += '00'

        try:
            dt = dateandtime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')

        except ValueError:
            raise error.PyAsn1Error('malformed datetime format %s' % self)

        return dt.replace(microsecond=ms, tzinfo=tzinfo)
1061780
def convert_time_string(date_str):
    
    dt, _, _ = date_str.partition(".")
    dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
    return dt
814819
def date(fmt=None,timestamp=None):
    ""
    if fmt=='U': # return timestamp
        t = datetime.datetime.now()
        return int(time.mktime(t.timetuple()))
    if fmt=='c': # return isoformat 
        d = datetime.datetime.fromtimestamp(timestamp)
        return d.isoformat()
    if fmt=='Ymd':
        d = datetime.datetime.now()
        return d.strftime("%Y%m%d")
770407
def parsetime(s):
    
    try:
        fields = s.split('.')
        subfields = fields[0].split(':')
        H = int(subfields[0])
        M = int(subfields[1])
        S = int(subfields[2])
        if len(subfields) > 3:
            m = int(subfields[3])
        else:
            m = 0
        if len(fields) > 1:
            m = int(fields[1])
        return (H,M,S,m)
    except:
        raise ValueError("Invalid timestamp, must be in HH:MM:SS.mmm format: " + s)
901410
function (timestamp) {
        var time = (new Date(timestamp)).toISOString();
        return {
            msg       : time,
            msgLength : time.length
        };
    }
1284255
def get_epoch_time_from_str(s):
    
    try:
        return int(s)
    except:
        pass

    try:
        if s.startswith('-'):
            chars = {'d': 24 * 60 * 60,
                     'h': 60 * 60,
                     'm': 60,
                     's': 1}
            m = chars.get(s[-1])
            if m:
                n = float(s[1:-1])
                secs = int(n * m)
                now = int(time.time())
                return max((now - secs), 0)
    except:
        pass

    raise ValueError("'%s' is an unrecognised time format." % s)
128956
def convert_timestamps(obj):
    
    for key in ('date', 'when', 'end', 'start_date', 'end_date'):
        value = obj.get(key)
        if value:
            try:
                obj[key] = _timestamp_to_dt(value)
            except TypeError:
                raise TypeError("expected float for %s, got %s" % (key, value))

    for key in ('sources', 'actions', 'votes', 'roles'):
        for child in obj.get(key, []):
            convert_timestamps(child)

    return obj
18711
def get_datetime(timestamp):
    
    timestamp_is_float = False
    try:
        float(timestamp)
        timestamp_is_float = True
    except (ValueError, TypeError):
        pass

    if timestamp_is_float == True:
        raise ValueError("Timestamp %s is a float"%(timestamp,))

    #First try to use date util. Failing that, continue
    try:
        parsed_dt = parse(timestamp, dayfirst=False)
        if parsed_dt.tzinfo is None:
            return parsed_dt
        else:

            return parsed_dt.replace(tzinfo=None)
    except:
        pass

    if isinstance(timestamp, datetime):
        return timestamp

    fmt = guess_timefmt(timestamp)
    if fmt is None:
        fmt = FORMAT

    # and proceed as usual
    try:
        ts_time = datetime.strptime(timestamp, fmt)
    except ValueError as e:
        if e.message.split(' ', 1)[0].strip() == 'unconverted':
            utcoffset = e.message.split()[3].strip()
            timestamp = timestamp.replace(utcoffset, '')
            ts_time = datetime.strptime(timestamp, fmt)
            # Apply offset
            tzoffset = timedelta(hours=int(utcoffset[0:3]),
                                          minutes=int(utcoffset[3:5]))
            ts_time -= tzoffset
        else:
            raise e

    return ts_time
648576
def convert_timestamp(timestamp):
    """"""
    timestamp = timestamp.strip()
    chunk, millis = timestamp.split(',')
    hours, minutes, seconds = chunk.split(':')
    hours = int(hours)
    minutes = int(minutes)
    seconds = int(seconds)
    seconds = seconds + hours * 60 * 60 + minutes * 60 + float(millis) / 1000
    return seconds