Parse a timezone specification in the [+|-]HHMM format.

    :return: the timezone offset in seconds.
15069
def parse_tz(tz):
    
    # from git_repository.py in bzr-git
    sign_byte = tz[0:1]
    # in python 3 b'+006'[0] would return an integer,
    # but b'+006'[0:1] return a new bytes string.
    if sign_byte not in (b'+', b'-'):
        raise ValueError(tz)

    sign = {b'+': +1, b'-': -1}[sign_byte]
    hours = int(tz[1:-2])
    minutes = int(tz[-2:])

    return sign * 60 * (60 * hours + minutes)
192160
def parse_datetime_aware(s, tz=None):
    
    assert settings.USE_TZ
    if isinstance(s, datetime.datetime):
        return s
    d = parse_datetime(s)
    if d is None:
        raise ValueError
    return timezone.make_aware(d, tz or timezone.get_current_timezone())
618103
def load_datetime(value, dt_format):
    
    if dt_format.endswith('%z'):
        dt_format = dt_format[:-2]
        offset = value[-5:]
        value = value[:-5]
        if offset != offset.replace(':', ''):
            # strip : from HHMM if needed (isoformat() adds it between HH and MM)
            offset = '+' + offset.replace(':', '')
            value = value[:-1]
        return OffsetTime(offset).localize(datetime.strptime(value, dt_format))

    return datetime.strptime(value, dt_format)
476167
def asDatetime(self, tzinfo=None):
        
        if tzinfo is None:
            tzinfo = FixedOffset(0, 0)

        if not self.isTimezoneDependent():
            return self._time.replace(tzinfo=tzinfo)
        else:
            return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo)
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
46063
def assert_tz_offset(tz):
    """"""
    tz_offset = get_tz_offset(tz)
    system_offset = get_system_offset()
    if tz_offset != system_offset:
        msg = ('Timezone offset does not match system offset: {0} != {1}. '
               'Please, check your config files.').format(
                   tz_offset, system_offset
               )
        raise ValueError(msg)
1134372
def Z(self):
    
    if not self.timezone:
      return 0
    offset = self.timezone.utcoffset(self.data)
    # Only days can be negative, so negative offsets have days=-1 and
    # seconds positive. Positive offsets have days=0
    return offset.days * 86400 + offset.seconds
1235259
def isoformat(self):
        
        text = [self.strftime('%Y-%m-%dT%H:%M:%S'), ]
        if self.tzinfo:
            text.append(self.tzinfo.as_timezone())
        else:
            text.append('+00:00')
        return ''.join(text)
419433
def _timedeltaToSignHrMin(offset):
    
    minutes = round((offset.days * 3600000000 * 24
                     + offset.seconds * 1000000
                     + offset.microseconds)
                    / 60000000.0)
    if minutes < 0:
        sign = '-'
        minutes = -minutes
    else:
        sign = '+'
    return (sign, minutes // 60, minutes % 60)
210794
function parseTimezoneOffset (offset) {
  let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/)
  minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes))
  return negateExceptForZero(minutes)
}
1307570
def _get_offset_time(utc_offset):
    '''
    
    '''
    if utc_offset is not None:
        minutes = _offset_to_min(utc_offset)
        offset = timedelta(minutes=minutes)
        offset_time = datetime.utcnow() + offset
        offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes))
    else:
        offset_time = datetime.now()
    return offset_time
1311275
def parse_timezone(matches, default_timezone=UTC):
    

    if matches["timezone"] == "Z":
        return UTC
    # This isn't strictly correct, but it's common to encounter dates without
    # timezones so I'll assume the default (which defaults to UTC).
    # Addresses issue 4.
    if matches["timezone"] is None:
        return default_timezone
    sign = matches["tz_sign"]
    hours = to_int(matches, "tz_hour")
    minutes = to_int(matches, "tz_minute", default_to_zero=True)
    description = "%s%02d:%02d" % (sign, hours, minutes)
    if sign == "-":
        hours = -hours
        minutes = -minutes
    return FixedOffset(hours, minutes, description)
21197
def parse_seconds(value):
        '''
        
        '''
        svalue = str(value)
        colons = svalue.count(':')
        if colons == 2:
            hours, minutes, seconds = [int(v) for v in svalue.split(':')]
        elif colons == 1:
            hours, minutes = [int(v) for v in svalue.split(':')]
            seconds = 0
        elif colons == 0:
            hours = 0
            minutes = 0
            seconds = int(svalue)
        else:
            raise ValueError('Must be in seconds or HH:MM:SS format')
        return Seconds.from_hms(hours, minutes, seconds)
528951
private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {
        try {
            TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);
            if (temporal instanceof OffsetDateTime) {
                OffsetDateTime odt = (OffsetDateTime) temporal;
                return Interval.of(start, odt.toInstant());
            } else {
                // infer offset from start if not specified by end
                LocalDateTime ldt = (LocalDateTime) temporal;
                return Interval.of(start, ldt.toInstant(offset));
            }
        } catch (DateTimeParseException ex) {
            Instant end = Instant.parse(endStr);
            return Interval.of(start, end);
        }
    }
402748
private String formatOffsetLocalizedGMT(int offset, boolean isShort) {
        if (offset == 0) {
            return _gmtZeroFormat;
        }

        StringBuilder buf = new StringBuilder();
        boolean positive = true;
        if (offset < 0) {
            offset = -offset;
            positive = false;
        }

        int offsetH = offset / MILLIS_PER_HOUR;
        offset = offset % MILLIS_PER_HOUR;
        int offsetM = offset / MILLIS_PER_MINUTE;
        offset = offset % MILLIS_PER_MINUTE;
        int offsetS = offset / MILLIS_PER_SECOND;

        if (offsetH > MAX_OFFSET_HOUR || offsetM > MAX_OFFSET_MINUTE || offsetS > MAX_OFFSET_SECOND) {
            throw new IllegalArgumentException("Offset out of range :" + offset);
        }

        Object[] offsetPatternItems;
        if (positive) {
            if (offsetS != 0) {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.POSITIVE_HMS.ordinal()];
            } else if (offsetM != 0 || !isShort) {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.POSITIVE_HM.ordinal()];
            } else {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.POSITIVE_H.ordinal()];
            }
        } else {
            if (offsetS != 0) {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.NEGATIVE_HMS.ordinal()];
            } else if (offsetM != 0 || !isShort) {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.NEGATIVE_HM.ordinal()];
            } else {
                offsetPatternItems = _gmtOffsetPatternItems[GMTOffsetPatternType.NEGATIVE_H.ordinal()];
            }
        }

        // Building the GMT format string
        buf.append(_gmtPatternPrefix);

        for (Object item : offsetPatternItems) {
            if (item instanceof String) {
                // pattern literal
                buf.append((String)item);
            } else if (item instanceof GMTOffsetField) {
                // Hour/minute/second field
                GMTOffsetField field = (GMTOffsetField)item;
                switch (field.getType()) {
                case 'H':
                    appendOffsetDigits(buf, offsetH, (isShort ? 1 : 2));
                    break;
                case 'm':
                    appendOffsetDigits(buf, offsetM, 2);
                    break;
                case 's':
                    appendOffsetDigits(buf, offsetS, 2);
                    break;
                }
            }
        }
        buf.append(_gmtPatternSuffix);
        return buf.toString();
    }
1026435
def parse_datetime(src=None):
    """"""
    if src is None:
        return None
    string = src.replace('"', "")
    # parse timezone ourselves, since %z is not always supported
    # see: http://bugs.python.org/issue6641
    m = UTC_OFFSET_RE.match(string)
    if m:
        sign = 1 if m.group("sign") == "+" else -1
        tz_hours = sign * int(m.group("hours"))
        tz_minutes = sign * int(m.group("minutes"))
        offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
        string = string[:-6]
    else:
        # no explicit timezone
        offset = datetime.timedelta(0)
    if "AM" in string or "PM" in string:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %I:%M:%S %p")
    else:
        datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
    return datetime_obj + offset
1104482
def parse_timestamp(ts_str):
	''''''
	assert isinstance(ts_str, bytes), [type(ts_str), repr(ts_str)]
	ts_str = ts_str.replace('_', ' ')

	# Try to parse time offset in short format
	match = _short_ts_regexp.search(ts_str)
	if match and any(match.groups()):
		delta = list()
		parse_int = lambda v: int(''.join(c for c in v if c.isdigit()))
		for units in [_short_ts_days, _short_ts_s]:
			val = 0
			for k, v in units.iteritems():
				try:
					if not match.group(k): continue
					n = parse_int(match.group(k))
				except IndexError: continue
				val += n * v
			delta.append(val)
		return timezone.localtime(timezone.now()) - timedelta(*delta)

	# Fallback to other generic formats
	ts = None
	if not ts:
		match = re.search( # common BE format
			r'^(?P<date>(?:\d{2}|(?P<Y>\d{4}))-\d{2}-\d{2})'
			r'(?:[ T](?P<time>\d{2}(?::\d{2}(?::\d{2})?)?)?)?$', ts_str )
		if match:
			tpl = 'y' if not match.group('Y') else 'Y'
			tpl, ts_str = '%{}-%m-%d'.format(tpl), match.group('date')
			if match.group('time'):
				tpl_time = ['%H', '%M', '%S']
				ts_str_time = match.group('time').split(':')
				ts_str += ' ' + ':'.join(ts_str_time)
				tpl += ' ' + ':'.join(tpl_time[:len(ts_str_time)])
			try: ts = timezone.make_aware(datetime.strptime(ts_str, tpl))
			except ValueError: pass
	if not ts:
		# coreutils' "date" parses virtually everything, but is more expensive to use
		with open(os.devnull, 'w') as devnull:
			proc = subprocess.Popen(
				['date', '+%s', '-d', ts_str],
				stdout=subprocess.PIPE, stderr=devnull, close_fds=True )
			val = proc.stdout.read()
			if not proc.wait():
				ts = timezone.make_aware(datetime.fromtimestamp(int(val.strip())))

	if ts: return ts
	raise ValueError('Unable to parse date/time string: {0}'.format(ts_str))