Turn a string timestamp into a date time. First tries to use dateutil.
        Failing that it tries to guess the time format and converts it manually
        using stfptime.

        @returns: A timezone unaware timestamp.
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
234396
def timestamp_to_datetime(cls, time_stamp, localized=True):
        
        ret = datetime.datetime.utcfromtimestamp(time_stamp)
        if localized:
            ret = localize(ret, pytz.utc)
        return ret
892137
def get_timestamp(cls, time_string: str, fmt: str):
        
        return int(time.mktime(time.strptime(time_string, fmt)))
652554
def parse_time(timestring):
    
    timestring = str(timestring).strip()

    for regex, pattern in TIME_FORMATS:
        if regex.match(timestring):
            found = regex.search(timestring).groupdict()

            dt = datetime.utcnow().strptime(found['matched'], pattern)
            dt = datetime.combine(date.today(), dt.time())

            if 'fraction' in found and found['fraction'] is not None:
                dt = dt.replace(microsecond=int(found['fraction'][1:]))

            if 'timezone' in found and found['timezone'] is not None:
                dt = dt.replace(tzinfo=Timezone(found.get('timezone', '')))

            return dt

    raise ParseError()
482245
def datetime_to_timestamp(time: datetime) -> Timestamp:
    
    protime = Timestamp()
    protime.FromDatetime(time)
    return protime
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"
        )
114728
def get_time_from_str(when):
    
    zero_oclock_today = datetime.now(tzlocal()).replace(
            hour=0, minute=0, second=0, microsecond=0)

    try:
        event_time = dateutil_parse(when, default=zero_oclock_today)
    except ValueError:
        struct, result = fuzzy_date_parse(when)
        if not result:
            raise ValueError('Date and time is invalid: %s' % (when))
        event_time = datetime.fromtimestamp(time.mktime(struct), tzlocal())

    return event_time
1178401
def from_format(
    string,  # type: str
    fmt,  # type: str
    tz=UTC,  # type: Union[str, _Timezone]
    locale=None,  # type: Union[str, None]
):  # type: (...) -> DateTime
    
    parts = _formatter.parse(string, fmt, now(), locale=locale)
    if parts["tz"] is None:
        parts["tz"] = tz

    return datetime(**parts)
234370
def from_iso_datetime(datetimestring, use_dateutil=True):
    
    if not _iso8601_datetime_re.match(datetimestring):
        raise ValueError('Not a valid ISO8601-formatted datetime string')
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.isoparse(datetimestring)
    else:
        # Strip off timezone info.
        return datetime.datetime.strptime(datetimestring[:19], '%Y-%m-%dT%H:%M:%S')
265281
def format_date(cls, timestamp):
        
        if not timestamp:
            raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))

        return timestamp.strftime(cls.DATE_FORMAT)
538572
def convert_to_utc(time):
        

        # time is already in UTC
        if 'Z' in time:
            return time
        else:
            time_formatted = time[:-3] + time[-2:]
            dt = datetime.strptime(time_formatted, '%Y-%m-%dT%H:%M:%S%z')
            dt = dt.astimezone(timezone('UTC'))
            return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
294541
def to_utc_datetime(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            value = self.to_naive_datetime(value)

        if isinstance(value, datetime.datetime):
            if timezone.is_naive(value):
                value = timezone.make_aware(value, timezone.utc)
            else:
                value = timezone.localtime(value, timezone.utc)
            return value

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to python data type" % value,
            code="invalid_datetime"
        )
721182
def dateTimeToString(dateTime, convertToUTC=False):
    
    if dateTime.tzinfo and convertToUTC:
        dateTime = dateTime.astimezone(utc)

    datestr = "{}{}{}T{}{}{}".format(
        numToDigits(dateTime.year, 4),
        numToDigits(dateTime.month, 2),
        numToDigits(dateTime.day, 2),
        numToDigits(dateTime.hour, 2),
        numToDigits(dateTime.minute, 2),
        numToDigits(dateTime.second, 2),
    )
    if tzinfo_eq(dateTime.tzinfo, utc):
        datestr += "Z"
    return datestr
412377
def datetime_to_timestamp(dt):
    

    epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
    return (dt - epoch).total_seconds()
1161540
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
        """"""
        return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
128003
def timestamp_from_datetime(dt):
    
    try:
        utc_dt = dt.astimezone(pytz.utc)
    except ValueError:
        utc_dt = dt.replace(tzinfo=pytz.utc)
    return timegm(utc_dt.timetuple())
107145
def strptime(self, value, format):
        

        value = force_str(value)
        if format == ISO_8601:
            try:
                parsed = parse_datetime(value)
                if not settings.USE_TZ:
                        fr_tz = pytz.timezone(settings.TIME_ZONE)
                        parsed = parsed.astimezone(fr_tz).replace(tzinfo=None)
            except:
                raise APIException(
                    "date parsing error: since parameter use the date format ISO 8601 (ex: 2014-11-18T15:56:58Z)")

            if parsed is None:
                raise APIException(
                    "since parameter use the date format ISO 8601 (ex: 2014-11-18T15:56:58Z)")
            return parsed
        return super(IsoDateTimeField, self).strptime(value, format)