Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch.
352257
def datetime_to_nanos(dt):
    
    if isinstance(dt, pd.Timestamp):
        return dt.value
    elif isinstance(dt, str):
        return pd.Timestamp(dt).value
    elif isinstance(dt, long):
        return dt
    elif isinstance(dt, datetime):
	return long(dt.strftime("%s%f")) * 1000

    raise ValueError
844432
def parse_string(self, timestr, subfmts):
        """"""
        # Datetime components required for conversion to JD by ERFA, along
        # with the default values.
        components = ('year', 'mon', 'mday')
        defaults = (None, 1, 1, 0)
        # Assume that anything following "." on the right side is a
        # floating fraction of a second.
        try:
            idot = timestr.rindex('.')
        except:
            fracday = 0.0
        else:
            timestr, fracday = timestr[:idot], timestr[idot:]
            fracday = float(fracday)

        for _, strptime_fmt_or_regex, _ in subfmts:
            vals = []
            #print strptime_fmt_or_regex
            if isinstance(strptime_fmt_or_regex, six.string_types):
                try:
                    #print timstr
                    #print strptime_fmt_or_regex
                    tm = time.strptime(timestr, strptime_fmt_or_regex)
                    tm.tm_hour += int(24 * fracday)
                    tm.tm_min += int(60 * (24 * fracday - tm.tm_hour))
                    tm.tm_sec += 60 * (60 * (24 * fracday - tm.tm_hour) - tm.tm_min)
                except ValueError as ex:
                    print ex
                    continue
                else:
                    vals = [getattr(tm, 'tm_' + component)
                            for component in components]

            else:
                tm = re.match(strptime_fmt_or_regex, timestr)
                if tm is None:
                    continue
                tm = tm.groupdict()
                vals = [int(tm.get(component, default)) for component, default
                        in six.moves.zip(components, defaults)]

                hrprt = int(24 * fracday)
                vals.append(hrprt)
                mnprt = int(60 * (24 * fracday - hrprt))
                vals.append(mnprt)
                scprt = 60 * (60 * (24 * fracday - hrprt) - mnprt)
                vals.append(scprt)
            return vals
        else:
            raise ValueError('Time {0} does not match {1} format'
                             .format(timestr, self.name))
34728
def is_valid_timestamp(date, unit='millis'):
    
    assert isinstance(date, int), "Input is not instance of int"

    if unit is 'millis':
        return is_positive(date) and len(str(date)) == 13
    elif unit is 'seconds':
        return is_positive(date) and len(str(date)) == 10
    else:
        raise ValueError('Unknown unit "%s"' % unit)
456290
def get_timestamp(length):
    """"""
    s = '%.6f' % time.time()
    whole, frac = map(int, s.split('.'))
    res = '%d%d' % (whole, frac)
    return res[:length]
1283365
def timestamp_long_from_uuid(uuid_arg):
    
    if isinstance(uuid_arg, str):
        uuid_arg = UUID(uuid_arg)
    assert isinstance(uuid_arg, UUID), uuid_arg
    uuid_time = uuid_arg.time
    return uuid_time - 0x01B21DD213814000
1132951
def epoch(ctx, datetime):
    
    return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx)
1258634
private static long getRawTimestamp(long timeMillis) {
        checkArgument(timeMillis >= TIME_MILLIS_MIN, "Time value too small.");  // < 12am Oct 15, 1582 (UTC)
        checkArgument(timeMillis <= TIME_MILLIS_MAX, "Time value too large.");  // > 9:21pm Mar 31, 5236 (UTC)
        return timeMillis * 10000 + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH;
    }
1104482
def parse_timestamp(ts_str):
	''''''
	assert isinstance(ts_str, bytes), [type(ts_str), repr(ts_str)]
	ts_str = ts_str.replace('_', ' ')

	# Try to parse time offset in short format
	match = _short_ts_regexp.search(ts_str)
	if match and any(match.groups()):
		delta = list()
		parse_int = lambda v: int(''.join(c for c in v if c.isdigit()))
		for units in [_short_ts_days, _short_ts_s]:
			val = 0
			for k, v in units.iteritems():
				try:
					if not match.group(k): continue
					n = parse_int(match.group(k))
				except IndexError: continue
				val += n * v
			delta.append(val)
		return timezone.localtime(timezone.now()) - timedelta(*delta)

	# Fallback to other generic formats
	ts = None
	if not ts:
		match = re.search( # common BE format
			r'^(?P<date>(?:\d{2}|(?P<Y>\d{4}))-\d{2}-\d{2})'
			r'(?:[ T](?P<time>\d{2}(?::\d{2}(?::\d{2})?)?)?)?$', ts_str )
		if match:
			tpl = 'y' if not match.group('Y') else 'Y'
			tpl, ts_str = '%{}-%m-%d'.format(tpl), match.group('date')
			if match.group('time'):
				tpl_time = ['%H', '%M', '%S']
				ts_str_time = match.group('time').split(':')
				ts_str += ' ' + ':'.join(ts_str_time)
				tpl += ' ' + ':'.join(tpl_time[:len(ts_str_time)])
			try: ts = timezone.make_aware(datetime.strptime(ts_str, tpl))
			except ValueError: pass
	if not ts:
		# coreutils' "date" parses virtually everything, but is more expensive to use
		with open(os.devnull, 'w') as devnull:
			proc = subprocess.Popen(
				['date', '+%s', '-d', ts_str],
				stdout=subprocess.PIPE, stderr=devnull, close_fds=True )
			val = proc.stdout.read()
			if not proc.wait():
				ts = timezone.make_aware(datetime.fromtimestamp(int(val.strip())))

	if ts: return ts
	raise ValueError('Unable to parse date/time string: {0}'.format(ts_str))
660421
def prepare_timestamp_micros(data, schema):
    """"""
    if isinstance(data, datetime.datetime):
        if data.tzinfo is not None:
            delta = (data - epoch)
            return int(delta.total_seconds() * MCS_PER_SECOND)
        t = int(time.mktime(data.timetuple())) * MCS_PER_SECOND + \
            data.microsecond
        return t
    else:
        return data
1344236
def from_str(duration):
    """"""

    if duration in ("0", "+0", "-0"):
        return datetime.timedelta()

    pattern = re.compile('([\d\.]+)([a-zµμ]+)')
    total = 0
    sign = -1 if duration[0] == '-' else 1
    matches = pattern.findall(duration)

    if not len(matches):
        raise Exception("Invalid duration {}".format(duration))

    for (value, unit) in matches:
        if unit not in units:
            raise Exception(
                "Unknown unit {} in duration {}".format(unit, duration))
        try:
            total += float(value) * units[unit]
        except:
            raise Exception(
                "Invalid value {} in duration {}".format(value, duration))

    microseconds = total / _microsecond_size
    return datetime.timedelta(microseconds=sign * microseconds)
503672
def ns2naturaltimesince(ns):
    
    timestamp = ns / 1000000000
    dt = datetime.datetime.utcfromtimestamp(timestamp)
    return dt2naturaltimesince(dt)
778300
def get_timestamp_info(value):
    
    value, offset = _split_offset(value)
    fmt, microsec = _get_timestamp_format(value)
    dt_value = _datetime_obj_factory(value, fmt)
    return dt_value, fmt, offset, microsec
97248
def CopyToDateTimeString(self):
    
    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(JavaTime, self).CopyToDateTimeString()
740836
def get_timestamp(str_len=13):
    
    if isinstance(str_len, integer_types) and 0 < str_len < 17:
        return builtin_str(time.time()).replace(".", "")[:str_len]

    raise ParamsError("timestamp length can only between 0 and 16.")
1120050
def parse_now_field(s):
    """"""
    if not s.startswith('UTC:'):
        return None  # Invalid string
    s = s[4:]

    # isoformat can return strings both with and without microseconds - we
    # account for both
    try:
        dt = datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
    except ValueError:
        dt = datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')

    return dt
1147239
def get_iso_time_str(timestamp: Union[int, float, str, datetime]=None) -> str:
    """"""
    if isinstance(timestamp, (int, float)):
        maya_dt = maya.MayaDT(timestamp)
    elif isinstance(timestamp, str):
        maya_dt = maya.when(timestamp)
    elif timestamp is None:
        maya_dt = maya.now()
    else:
        raise ValueError(f'`{type(timestamp)}` is not supported')
    return maya_dt.iso8601()
551359
def str2long(s):
    """"""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError('the input must be a string')

    l = 0
    for i in s:
        l <<= 8
        l |= ord(i)

    return l