Convert a datetime to a UTC timestamp w/ microsecond resolution.

        datetimes w/o timezone will be assumed to be in UTC
969888
def field_datetime_to_json(self, dt):
        
        if isinstance(dt, six.string_types):
            dt = parse_datetime(dt)
        if not dt:
            return None
        ts = timegm(dt.utctimetuple())
        if dt.microsecond:
            return "{0}.{1:0>6d}".format(ts, dt.microsecond)
        else:
            return ts
877005
def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
    """"""
    tz = pytz.timezone(timezone_name)
    tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
    timestamp = calendar.timegm(tz_datetime.utctimetuple())
    return timestamp
266050
def timestamp(self, timestamp):
        """"""
        if timestamp is None:
            self._timestamp = datetime.utcnow()
        elif isinstance(timestamp, datetime):
            self._timestamp = timestamp
        else:
            self._timestamp = datetime.strptime(timestamp, fmt)
921025
def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False):
    
    tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo)
    if keep_tzinfo is False:
        tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None)
    return tz_awared_datetime
41926
def date2timestamp(dte):
    ''''''
    seconds = mktime(dte.timetuple())
    if isinstance(dte, datetime):
        return seconds + dte.microsecond / 1000000.0
    else:
        return int(seconds)
139599
def _to_utc(self, dt):
        """"""
        tz = self._get_tz()
        loc_dt = tz.localize(dt)
        return loc_dt.astimezone(pytz.utc)
1287352
def utcfromtimestamp(cls, t):
        ""
        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us)
641392
def _time_to_datetime(value):
  
  if not isinstance(value, datetime.time):
    raise TypeError('Cannot convert to datetime expected time value; '
                    'received %s' % value)
  return datetime.datetime(1970, 1, 1,
                           value.hour, value.minute, value.second,
                           value.microsecond)
1359058
def timestamp(x):
    """"""
    if x.tzinfo is None:
        # Naive dates to utc
        x = x.replace(tzinfo=utc)

    if hasattr(x, 'timestamp'):
        return x.timestamp()
    else:
        return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
456704
def __consistent_isoformat_utc(datetime_val):
        
        isotime = datetime_val.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z")
        if isotime[-2] != ":":
            isotime = isotime[:-2] + ":" + isotime[-2:]
        return isotime
899681
def TimestampToRDFDatetime(timestamp):
  """"""
  # TODO(hanuszczak): `timestamp` should be of MySQL type `Decimal`. However,
  # it is unclear where this type is actually defined and how to import it in
  # order to have a type assertion.
  if timestamp is None:
    return None
  else:
    micros = int(1000000 * timestamp)
    return rdfvalue.RDFDatetime.FromMicrosecondsSinceEpoch(micros)
1205671
def _convert_to_datetime(unix_timestamp):
    '''
    
    '''
    try:
        unix_timestamp = float(unix_timestamp)
        return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        return 'Invalid Timestamp'
1109555
def datetime(
    year,  # type: int
    month,  # type: int
    day,  # type: int
    hour=0,  # type: int
    minute=0,  # type: int
    second=0,  # type: int
    microsecond=0,  # type: int
    tz=UTC,  # type: Union[str, _Timezone]
    dst_rule=POST_TRANSITION,  # type: str
):  # type: (...) -> DateTime
    
    if tz is not None:
        tz = _safe_timezone(tz)

    if not _HAS_FOLD:
        dt = naive(year, month, day, hour, minute, second, microsecond)
    else:
        dt = _datetime.datetime(year, month, day, hour, minute, second, microsecond)
    if tz is not None:
        dt = tz.convert(dt, dst_rule=dst_rule)

    return DateTime(
        dt.year,
        dt.month,
        dt.day,
        dt.hour,
        dt.minute,
        dt.second,
        dt.microsecond,
        tzinfo=dt.tzinfo,
        fold=dt.fold,
    )
1035531
def from_utc(utcTime, fmt=None):
    """"""
    if fmt is None:
        try_formats = ["%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"]
    else:
        try_formats = [fmt]

    for fmt in try_formats:
        try:
            time_struct = datetime.datetime.strptime(utcTime, fmt)
        except ValueError:
            pass
        else:
            date = int(time.mktime(time_struct.timetuple()))
            return date
    else:
        raise ValueError("No UTC format matches {}".format(utcTime))
909862
def to_timestamp(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return int(value)
            except ValueError:
                value = self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            if timezone.is_aware(value):
                value = timezone.localtime(value, timezone.utc)
            return self._datetime_to_timestamp(value)

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to timestamp" % value,
            code="invalid_timestamp"
        )
941030
def set_timestamp(self, timestamp=str(datetime.datetime.utcfromtimestamp(time.time()))):
        
        self.timestamp = timestamp
504326
def _datetime_to_utc(self, dt):
        """"""

        if not dt.tzinfo:
            dt = dt.replace(tzinfo=tz.gettz())
        return dt.astimezone(tz.gettz('UTC'))