Normalize time in arbitrary timezone to UTC naive object.
554596
def normalize_time(timestamp):
    """"""
    offset = timestamp.utcoffset()
    if offset is None:
        return timestamp
    return timestamp.replace(tzinfo=None) - offset
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
835348
def _process_tz(self, dt, naive, tz):
		""""""
		
		def _tz(t):
			if t in (None, 'naive'):
				return t
			
			if t == 'local':
				if __debug__ and not localtz:
					raise ValueError("Requested conversion to local timezone, but `localtz` not installed.")
				
				t = localtz
			
			if not isinstance(t, tzinfo):
				if __debug__ and not localtz:
					raise ValueError("The `pytz` package must be installed to look up timezone: " + repr(t))
				
				t = get_tz(t)
			
			if not hasattr(t, 'normalize') and get_tz:  # Attempt to handle non-pytz tzinfo.
				t = get_tz(t.tzname(dt))
			
			return t
		
		naive = _tz(naive)
		tz = _tz(tz)
		
		if not dt.tzinfo and naive:
			if hasattr(naive, 'localize'):
				dt = naive.localize(dt)
			else:
				dt = dt.replace(tzinfo=naive)
		
		if not tz:
			return dt
		
		if hasattr(tz, 'normalize'):
			dt = tz.normalize(dt.astimezone(tz))
		elif tz == 'naive':
			dt = dt.replace(tzinfo=None)
		else:
			dt = dt.astimezone(tz)  # Warning: this might not always be entirely correct!
		
		return dt
838469
def _(obj):
    """"""

    tz_offset = obj.utcoffset()

    if not tz_offset or tz_offset == UTC_ZERO:
        iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    else:
        iso_datetime = obj.isoformat()

    return iso_datetime
728899
def utc_minute_timezone(self, minutes_from_utc):
        """"""
        from_zone = tz.gettz('UTC')
        to_zone = self.location.timezone
        utc = dt.datetime.combine(self.date, dt.time()) + \
            dt.timedelta(minutes=minutes_from_utc)
        utc = utc.replace(tzinfo=from_zone)
        local = utc.astimezone(to_zone)
        return local
286037
def altz_to_utctz_str(altz):
    """"""
    utci = -1 * int((float(altz) / 3600) * 100)
    utcs = str(abs(utci))
    utcs = "0" * (4 - len(utcs)) + utcs
    prefix = (utci < 0 and '-') or '+'
    return prefix + utcs
1017959
def to_epoch(t):
    """"""
    if isinstance(t, str):
        if '+' not in t:
            t = t + '+00:00'
        t = parser.parse(t)
    elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None:
        t = t.replace(tzinfo=pytz.timezone('utc'))

    t0 = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, pytz.timezone('utc'))
    delta = t - t0
    return int(delta.total_seconds())
205241
def _to_timezone(self, dt):
        """"""
        tz = self._get_tz()
        utc_dt = pytz.utc.localize(dt)
        return utc_dt.astimezone(tz)
587188
def _utc_float(self):
        """"""
        tai = self.tai
        leap_dates = self.ts.leap_dates
        leap_offsets = self.ts.leap_offsets
        leap_reverse_dates = leap_dates + leap_offsets / DAY_S
        i = searchsorted(leap_reverse_dates, tai, 'right')
        return tai - leap_offsets[i] / DAY_S
867551
def to_localtime(time):
    ''''''

    utc_time = time.replace(tzinfo=timezone.utc)
    to_zone = timezone.get_default_timezone()
    return utc_time.astimezone(to_zone)
639084
def fromtimestamp(cls, timestamp):
    """"""
    d = cls.utcfromtimestamp(timestamp)
    return d.astimezone(localtz())
1268049
def __to_localdatetime(val):
    """"""
    try:
        dt = datetime.strptime(val, __DATE_FORMAT)
        dt = pytz.timezone(__TIMEZONE).localize(dt)
        return dt
    except (ValueError, TypeError):
        return None
1324586
def utc_to_local(time_str, use_12_hour_format, show_datetime=False):
        """"""
        if not (time_str.endswith(" UTC") or time_str.endswith("Z")):
            return time_str

        today_utc = datetime.datetime.utcnow()
        utc_local_diff = today_utc - datetime.datetime.now()

        if time_str.endswith(" UTC"):
            time_str, _ = time_str.split(" UTC")
            utc_time = datetime.datetime.strptime(time_str, '%I:%M %p')
            utc_datetime = datetime.datetime(today_utc.year,
                                             today_utc.month,
                                             today_utc.day,
                                             utc_time.hour,
                                             utc_time.minute)
        else:
            utc_datetime = datetime.datetime.strptime(time_str,
                                                      '%Y-%m-%dT%H:%M:%SZ')

        local_time = utc_datetime - utc_local_diff

        if use_12_hour_format:
            date_format = '%I:%M %p' if not show_datetime else '%a %d, %I:%M %p'
        else:
            date_format = '%H:%M' if not show_datetime else '%a %d, %H:%M'

        return datetime.datetime.strftime(local_time, date_format)
1213200
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
    
    if to_tz is None:
        to_tz = settings.TIME_ZONE
    if value.tzinfo is None:
        if not hasattr(from_tz, "localize"):
            from_tz = pytz.timezone(smart_str(from_tz))
        value = from_tz.localize(value)
    return value.astimezone(pytz.timezone(smart_str(to_tz)))
89729
def _parse_datetime_value(value):
    """"""
    if value.endswith('Z'):
        # Arrow doesn't support the "Z" literal to denote UTC time.
        # Strip the "Z" and add an explicit time zone instead.
        value = value[:-1] + '+00:00'

    return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
1328463
def to_datetime(dt, tzinfo=None, format=None):
    
    if not dt:
        return dt
    
    tz = pick_timezone(tzinfo, __timezone__)
    
    if isinstance(dt, (str, unicode)):
        if not format:
            formats = DEFAULT_DATETIME_INPUT_FORMATS
        else:
            formats = list(format)
        d = None
        for fmt in formats:
            try:
                d = datetime.strptime(dt, fmt)
            except ValueError:
                continue
        if not d:
            return None
        d = d.replace(tzinfo=tz)
    else:
        d = datetime(getattr(dt, 'year', 1970), getattr(dt, 'month', 1),
            getattr(dt, 'day', 1), getattr(dt, 'hour', 0), getattr(dt, 'minute', 0),
            getattr(dt, 'second', 0), getattr(dt, 'microsecond', 0))
        if not getattr(dt, 'tzinfo', None):
            d = d.replace(tzinfo=tz)
        else:
            d = d.replace(tzinfo=dt.tzinfo)
    return to_timezone(d, tzinfo)
1263304
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
    
    tz_offset = datetime_to_timezone(
        datetime.datetime.now(), tz=tz_from).strftime('%z')
    tz_offset = tz_offset[:3] + ':' + tz_offset[3:]

    date = parse_date(str(date_str) + tz_offset)
    if tz_from != tz_to:
        date = datetime_to_timezone(date, tz_to)

    if isinstance(fmt, str):
        return date.strftime(fmt)
    return date