Compares local timezone offset to pytz's timezone db, to determine
    a matching timezone name to use when TIME_ZONE is not set.
545100
def get_best_local_timezone():
    
    zone_name = tzlocal.get_localzone().zone
    if zone_name in pytz.all_timezones:
        return zone_name
    if time.daylight:
        local_offset = time.altzone
        localtz = time.tzname[1]
    else:
        local_offset = time.timezone
        localtz = time.tzname[0]
    local_offset = datetime.timedelta(seconds=-local_offset)
    for zone_name in pytz.all_timezones:
        timezone = pytz.timezone(zone_name)
        if not hasattr(timezone, '_tzinfos'):
            continue
        for utcoffset, daylight, tzname in timezone._tzinfos:
            if utcoffset == local_offset and tzname == localtz:
                return zone_name
225971
def timezone(self, value):
        """"""
        self._timezone = (value if isinstance(value, datetime.tzinfo)
                          else tz.gettz(value))
156573
def to_timezone(dt, tzinfo=None):
    
    if not dt:
        return dt
    tz = pick_timezone(tzinfo, __timezone__)
    if not tz:
        return dt
    dttz = getattr(dt, 'tzinfo', None)
    if not dttz:
        return dt.replace(tzinfo=tz)
    else:
        return dt.astimezone(tz)
469043
def local_timezone(value):
    """"""
    if hasattr(value, "tzinfo") and value.tzinfo is None:
        return value.replace(tzinfo=dateutil.tz.tzlocal())
    return value
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)))
316192
def GetTZInfo(tzname='UTC', utcOffset=None, dst=None):
      
      key = (tzname, utcOffset, dst)
      tzInfo = TZManager._tzInfos.get(key)
      if not tzInfo:
         tzInfo = TZInfo(tzname, utcOffset, dst)
         TZManager._tzInfos[key] = tzInfo
      return tzInfo
564833
def in_timezone(self, tz):  # type: (Union[str, Timezone]) -> DateTime
        
        tz = pendulum._safe_timezone(tz)

        return tz.convert(self, dst_rule=pendulum.POST_TRANSITION)
1252614
def datetime_timezone(tz):
    
    utc_datetime_naive = datetime.utcnow()
    # return a localized datetime to UTC
    utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
    # normalize the datetime to given timezone
    normalized_datetime = normalize(utc_localized_datetime, tz)
    return normalized_datetime
1053471
def timezone_from_str(tz_str):
    
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    if m:
        # in format 'UTC±[hh]:[mm]'
        delta_h = int(m.group(1))
        delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
        return timezone(timedelta(hours=delta_h, minutes=delta_m))

    # in format 'Asia/Shanghai'
    try:
        return pytz.timezone(tz_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None
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
818497
def get_offset(target):
    
    from pytz import timezone
    import pytz
    from datetime import datetime

    utc = pytz.utc

    today = datetime.now()
    tz_target = timezone(tf.certain_timezone_at(lat=target['lat'], lng=target['lng']))
    # ATTENTION: tz_target could be None! handle error case
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    return (today_utc - today_target).total_seconds() / 60
1244473
def _min_timezone_offset():
    ""
    now = time.time()
    return (datetime.datetime.fromtimestamp(now) - datetime.datetime.utcfromtimestamp(now)).seconds // 60
880972
def set_timezone(data, tz=None, from_local=False):
    
    # pandas object?
    if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series):
        try:
            try:
                data.index = data.index.tz_convert(tz)
            except Exception as e:
                if from_local:
                    data.index = data.index.tz_localize(
                        get_timezone()).tz_convert(tz)
                else:
                    data.index = data.index.tz_localize('UTC').tz_convert(tz)
        except Exception as e:
            pass

    # not pandas...
    else:
        if isinstance(data, str):
            data = parse_date(data)
        try:
            try:
                data = data.astimezone(tz)
            except Exception as e:
                data = timezone('UTC').localize(data).astimezone(timezone(tz))
        except Exception as e:
            pass

    return data
739037
def reload_localzone():
    """"""
    global _cache_tz
    _cache_tz = pytz.timezone(get_localzone_name())
    utils.assert_tz_offset(_cache_tz)
    return _cache_tz
1077037
def utc2local(date):
    
    date_offset = (datetime.now() - datetime.utcnow())
    # Python < 2.7 don't have the 'total_seconds' method so calculate it by hand!
    date_offset = (date_offset.microseconds +
                   (date_offset.seconds + date_offset.days * 24 * 3600) * 1e6) / 1e6
    date_offset = int(round(date_offset / 60 / 60))
    return date + timedelta(hours=date_offset)
909035
def now(tz=None):  # type: (Union[str, _Timezone, None]) -> DateTime
    
    if has_test_now():
        test_instance = get_test_now()
        _tz = _safe_timezone(tz)

        if tz is not None and _tz != test_instance.timezone:
            test_instance = test_instance.in_tz(_tz)

        return test_instance

    if tz is None or tz == "local":
        dt = _datetime.datetime.now(local_timezone())
    elif tz is UTC or tz == "UTC":
        dt = _datetime.datetime.now(UTC)
    else:
        dt = _datetime.datetime.now(UTC)
        tz = _safe_timezone(tz)
        dt = tz.convert(dt)

    return instance(dt, tz)
819022
def tzname(self, dt):
        """"""
        tt = _localtime(_mktime((dt.year, dt.month, dt.day,
                 dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
        return _time.tzname[tt.tm_isdst > 0]