Converts a millisecond accuracy timestamp to a datetime
976366
def ms_to_datetime(ms):
    
    dt = datetime.datetime.utcfromtimestamp(ms / 1000)
    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
454035
def convert_to_timestamp(time):
    """"""
    if time == -1:
        return None
    time = int(time*1000)
    hour = time//1000//3600
    minute = (time//1000//60) % 60
    second = (time//1000) % 60
    return str(hour).zfill(2)+":"+str(minute).zfill(2)+":"+str(second).zfill(2)
385131
def _timestamp_to_json_row(value):
    
    if isinstance(value, datetime.datetime):
        value = _microseconds_from_datetime(value) * 1e-6
    return value
370320
def iso8601timestamp(T=None, nanos=True, utc=False):
	""""""
	T  = time.time() if T is None else T
	Ti = math.floor(T)
	Tn = round((T-Ti)*1e9)
	if Tn >= 1e9:
		Ti += 1
		Tn  = 0
	
	s  = time.gmtime(Ti)      if utc   else time.localtime(Ti)
	f  = time.strftime("%Y%m%dT%H%M%S", s)
	n  = ".{:09d}".format(Tn) if nanos else ""
	tz = "Z"                  if utc   else time.strftime("%z", s)
	return f+n+tz
435006
def target_timestamp(self) -> datetime:
        """"""
        timestamp = DB.get_hash_value(self._key, 'target_timestamp')
        return datetime_from_isoformat(timestamp)
806988
def datetime_to_ms(d):
    """"""
    try:
        millisecond = d.microsecond // 1000
        return calendar.timegm(_add_tzone(d).utctimetuple()) * 1000 + millisecond
    except AttributeError:
        raise TypeError('expect Python datetime object, not %s' % type(d))
401007
def from_datetime(dt, machine_id=0):
        
        td = dt - Timestamp._EPOCH
        seconds = td.days * 3600 * 24
        seconds += td.seconds
        return Timestamp(seconds, td.microseconds*1000, machine_id)
1153096
def pretty_timestamp(timestamp, date_format='%a-%m_%d_%y:%H:%M:%S'):
    """"""
    return time.strftime(date_format,
                         time.localtime(int(str(timestamp)[:10])))
385569
def timestamp_normalized(self):
        
        if not self.timestamp:
            return None

        if isinstance(self.timestamp, six.integer_types):
            return self.timestamp

        if isinstance(self.timestamp, timedelta):
            tmp = datetime.now() + self.timestamp
        else:
            tmp = self.timestamp

        return int(time.mktime(tmp.timetuple()) * 1e+6 + tmp.microsecond)
142643
def hittime(cls, timestamp=None, age=None, milliseconds=None):
        
        if isinstance(timestamp, (int, float)):
            return int(Time.milliseconds_offset(Time.from_unix(timestamp, milliseconds=milliseconds)))
        if isinstance(timestamp, datetime.datetime):
            return int(Time.milliseconds_offset(timestamp))
        if isinstance(age, (int, float)):
            return int(age * 1000) + (milliseconds or 0)
547834
def to_timestamp(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return float(value)
            except ValueError:
                value = self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            return self._datetime_to_timestamp(value)

        if value is None:
            try:
                return float(self.default)
            except:
                return 0.0

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to timestamp" % value,
            code="invalid_timestamp"
        )
942893
def parse_timestamp(timestamp):
    """"""
    dt = dateutil.parser.parse(timestamp)
    return dt.astimezone(dateutil.tz.tzutc())
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
1110428
def __timestamp():
    """"""
    today = time.time()
    ret = struct.pack(b'=L', int(today))
    return ret
1190003
def prepare_timestamp_millis(data, schema):
    
    if isinstance(data, datetime.datetime):
        if data.tzinfo is not None:
            delta = (data - epoch)
            return int(delta.total_seconds() * MLS_PER_SECOND)
        t = int(time.mktime(data.timetuple())) * MLS_PER_SECOND + int(
            data.microsecond / 1000)
        return t
    else:
        return data
1089783
def _microseconds_from_datetime(value):
    
    if not value.tzinfo:
        value = value.replace(tzinfo=UTC)
    # Regardless of what timezone is on the value, convert it to UTC.
    value = value.astimezone(UTC)
    # Convert the datetime to a microsecond timestamp.
    return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond
661701
def _timestamp():
    """"""
    moment = time.time()
    moment_us = repr(moment).split('.')[1]
    return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment))