Localizes time range. Uses pytz.utc if None provided.
    :param begin: Begin datetime
    :param end: End datetime
    :param tz: pytz timezone or None (default UTC)
    :return: begin, end
540900
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime):
    
    if not tz:
        tz = pytz.utc
    return tz.localize(begin), tz.localize(end)
1010623
def convert_timezone(obj, timezone):
    
    if timezone is None:
        return obj.replace(tzinfo=None)
    return pytz.timezone(timezone).localize(obj)
47300
def _normalize_tz(val):
  
  match = _TZ_RE.match(val)
  if match:
    ts, tz = match.groups()
    if len(tz) == 5:
      # If the length of the tz is 5 then it is of the form (+|-)dddd, which is exactly what python
      # wants, so just return it.
      return ts + tz
    if len(tz) == 6:
      # If the length of the tz is 6 then it is of the form (+|-)dd:dd, just remove the colon
      return ts + tz[:3] + tz[4:]
    if tz == "Z" or tz == "z":
      # If the tz is "Z" or 'z', return a timezone of +0000
      return ts + "+0000"
    else:
      # Otherwise, the timzone must be of the format (+|-)dd, in which case we just need to add two
      # "0" to it, and it will be in the proper format.
      return ts + tz + "00"
  else:
    return val
682083
public void setTimeZone(TimeZone tz)
    {
        setTzFormatString(tz);        
        if( _locale != null ) 
        {
            _tzFormat=new SimpleDateFormat(_tzFormatString,_locale);
            _minFormat=new SimpleDateFormat(_minFormatString,_locale);
        }
        else if( _dfs != null ) 
        {
            _tzFormat=new SimpleDateFormat(_tzFormatString,_dfs);
            _minFormat=new SimpleDateFormat(_minFormatString,_dfs);
        }
        else 
        {
            _tzFormat=new SimpleDateFormat(_tzFormatString);
            _minFormat=new SimpleDateFormat(_minFormatString);
        }
        _tzFormat.setTimeZone(tz);
        _minFormat.setTimeZone(tz);
        _lastSeconds=-1;
        _lastMinutes=-1;        
    }
1299984
def _convertTZ(self):
        """"""
        tz = timezone.get_current_timezone()
        dtstart = self['DTSTART']
        dtend   = self['DTEND']
        if dtstart.zone() == "UTC":
            dtstart.dt = dtstart.dt.astimezone(tz)
        if dtend.zone() == "UTC":
            dtend.dt = dtend.dt.astimezone(tz)
308841
def initialize_time_zone
      if configuration.time_zone
        zone_default = Time.__send__(:get_zone, configuration.time_zone)

        unless zone_default
          raise \
            'Value assigned to config.time_zone not recognized.' +
            'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
        end

        Time.zone_default = zone_default

        if defined?(ActiveRecord)
          ActiveRecord::Base.time_zone_aware_attributes = true
          ActiveRecord::Base.default_timezone = :utc
        end
      end
    end
1071298
def _get_timezone(self, tz):
        
        # special Local timezone
        if tz == "Local":
            try:
                return tzlocal.get_localzone()
            except pytz.UnknownTimeZoneError:
                return "?"

        # we can use a country code to get tz
        # FIXME this is broken for multi-timezone countries eg US
        # for now we just grab the first one
        if len(tz) == 2:
            try:
                zones = pytz.country_timezones(tz)
            except KeyError:
                return "?"
            tz = zones[0]

        # get the timezone
        try:
            zone = pytz.timezone(tz)
        except pytz.UnknownTimeZoneError:
            return "?"
        return zone
137101
public final boolean between(@Nonnull UtcTime begin, @Nonnull UtcTime end) {
    return (time >= begin.time) && (time <= end.time);
  }
282977
def now(cls, tzinfo=None):
    """"""
    obj = cls.utcnow()
    if tzinfo is None:
      tzinfo = localtz()
    return obj.astimezone(tzinfo)
1219999
def get_now_utc():
    ''' '''

    # Helper class for UTC time
    # Source: http://stackoverflow.com/questions/2331592/datetime-datetime-utcnow-why-no-tzinfo
    ZERO = datetime.timedelta(0)
    class UTC(datetime.tzinfo):
        """UTC"""
        def utcoffset(self, dt):
            return ZERO
        def tzname(self, dt):
            return "UTC"
        def dst(self, dt):
            return ZERO

    #now = datetime.datetime.now(timezone.utc) # Python 3.2
    now = datetime.datetime.now(UTC())
    return now
91623
def timezone(name, extended=True):  # type: (Union[str, int]) -> _Timezone
    
    if isinstance(name, int):
        return fixed_timezone(name)

    if name.lower() == "utc":
        return UTC

    if name in _tz_cache:
        return _tz_cache[name]

    tz = _Timezone(name, extended=extended)
    _tz_cache[name] = tz

    return tz
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
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)
537401
def setup_timezone(timezone: str) -> None:
    
    if timezone and hasattr(time, 'tzset'):
        tz_root = '/usr/share/zoneinfo'
        tz_filename = os.path.join(tz_root, *(timezone.split('/')))

        if os.path.exists(tz_root) and not os.path.exists(tz_filename):
            raise ValueError('Incorrect timezone value: {0}'.format(timezone))

        os.environ['TZ'] = timezone
        time.tzset()
70114
def localize(self, dt, is_dst=False):
        """"""
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self)
1219576
def to_utc(value, defaulttz=None):
    
    if defaulttz is None:
        defaulttz = tzlocal()
    return _convert(value, tzutc(), defaulttz)
96670
public static long timestampCeil(TimeUnitRange range, long ts, TimeZone tz) {
		// assume that we are at UTC timezone, just for algorithm performance
		long offset = tz.getOffset(ts);
		long utcTs = ts + offset;

		switch (range) {
			case HOUR:
				return ceil(utcTs, MILLIS_PER_HOUR) - offset;
			case DAY:
				return ceil(utcTs, MILLIS_PER_DAY) - offset;
			case MONTH:
			case YEAR:
			case QUARTER:
				int days = (int) (utcTs / MILLIS_PER_DAY + EPOCH_JULIAN);
				return julianDateFloor(range, days, false) * MILLIS_PER_DAY - offset;
			default:
				// for MINUTE and SECONDS etc...,
				// it is more effective to use arithmetic Method
				throw new AssertionError(range);
		}
	}