Returns the SQL that will convert field_name to UTC from tzname.
347156
def _switch_tz_offset_sql(self, field_name, tzname):
        
        field_name = self.quote_name(field_name)
        if settings.USE_TZ:
            if pytz is None:
                from django.core.exceptions import ImproperlyConfigured
                raise ImproperlyConfigured("This query requires pytz, "
                                           "but it isn't installed.")
            tz = pytz.timezone(tzname)
            td = tz.utcoffset(datetime.datetime(2000, 1, 1))

            def total_seconds(td):
                if hasattr(td, 'total_seconds'):
                    return td.total_seconds()
                else:
                    return td.days * 24 * 60 * 60 + td.seconds

            total_minutes = total_seconds(td) // 60
            hours, minutes = divmod(total_minutes, 60)
            tzoffset = "%+03d:%02d" % (hours, minutes)
            field_name = "CAST(SWITCHOFFSET(TODATETIMEOFFSET(%s, '+00:00'), '%s') AS DATETIME2)" % (field_name, tzoffset)
        return field_name
185316
public static long convertToUtc(long millis, String tz)
    {
        long ret = millis;
        if(tz != null && tz.length() > 0)
        {
            DateTime dt = new DateTime(millis, DateTimeZone.forID(tz));
            ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis();
        }
        return ret;
    }
115836
def _get_timezone(self, root):
        """"""
        tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
        hours = int(self._tz_re.search(tz_str).group(1))
        return tzoffset(tz_str, hours * 60)
1126277
def getTimeZone(lat, lon):
    
    #Need to fix for Python 2.x and 3.X support
    import urllib.request, urllib.error, urllib.parse
    import xml.etree.ElementTree as ET
    #http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query.xml?points=37.78%2C-122.42%3B40.71%2C-74.01&databases=Point%2CTimeZone%2CAstronomy%2CNaturalEarthCountry%2CUsState2010%2CUsCounty2010%2CUsCountySubdivision2010%2CUsTract2010%2CUsBlockGroup2010%2CUsPlace2010%2CUsZcta2010
    req = "http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query.xml?points="+str(lat)+"%2C"+str(lon)+"&databases=TimeZone"
    opener = urllib.request.build_opener()
    f = opener.open(req)
    tree = ET.parse(f)
    root = tree.getroot()
    #Check response
    tzid = None
    if root.attrib['code'] == '0':
        tz = list(root.iter('TimeZone'))[0]
        #shortname = tz.attrib['ShortName']
        tzid = tz.attrib['TimeZoneId']
    return tzid
650381
def _tzinfome(tzinfo):
  
  if not isinstance(tzinfo, datetime.tzinfo):
    try:
      tzinfo = pytz.timezone(tzinfo)
      assert tzinfo.zone in pytz.all_timezones
    except AttributeError:
      raise pytz.UnknownTimeZoneError("Unknown timezone! %s" % tzinfo)
  return tzinfo
435905
def adjust_from_utc_fields(*args, **kwargs):
        """"""
        raw_ts = Timestamp(*args, **kwargs)
        offset = raw_ts.utcoffset()
        if offset is None or offset == timedelta():
            return raw_ts

        # XXX This returns a datetime, not a Timestamp (which has our precision if defined)
        adjusted = raw_ts + offset
        if raw_ts.precision is None:
            # No precision means we can just return a regular datetime
            return adjusted

        return Timestamp(
            adjusted.year,
            adjusted.month,
            adjusted.day,
            adjusted.hour,
            adjusted.minute,
            adjusted.second,
            adjusted.microsecond,
            raw_ts.tzinfo,
            precision=raw_ts.precision,
            fractional_precision=raw_ts.fractional_precision
        )
1335880
static PrefsTransform getSqlTransform(TypeName typeName) {
		if (Time.class.getName().equals(typeName.toString())) {
			return new SQLTimePrefsTransform();
		}
		
		if (java.sql.Date.class.getName().equals(typeName.toString())) {
			return new SQLDatePrefsTransform();
		}

		return null;
	}
1005956
def dbStore(self, typ, py_value):
        
        if isinstance(py_value, datetime.datetime):
            # ensure we have some timezone information before converting to UTC time
            if py_value.tzinfo is None:
                # match the server information
                tz = pytz.timezone(orb.system.settings().server_timezone)
                py_value = tz.localize(py_value)
            return py_value.astimezone(pytz.utc).replace(tzinfo=None)
        else:
            return super(DatetimeWithTimezoneColumn, self).dbStore(typ, py_value)
382760
def get_utc_timestamp(self, handle):
        """"""
        fpath = self._fpath_from_handle(handle)
        datetime_obj = datetime.datetime.utcfromtimestamp(
            os.stat(fpath).st_mtime
        )
        return timestamp(datetime_obj)
759890
def get_zonecode():
    '''
    
    '''
    tz_object = pytz.timezone(get_zone())
    loc_time = tz_object.localize(datetime.utcnow())
    return loc_time.tzname()
996636
def get_db_prep_save(self, value, connection=None):
        
        ## convert to settings.TIME_ZONE
        if value is not None:
            if value.tzinfo is None:
                value = default_tz.localize(value)
            else:
                value = value.astimezone(default_tz)
        return super(LocalizedDateTimeField, self).get_db_prep_save(value, connection=connection)
1219576
def to_utc(value, defaulttz=None):
    
    if defaulttz is None:
        defaulttz = tzlocal()
    return _convert(value, tzutc(), defaulttz)
205241
def _to_timezone(self, dt):
        """"""
        tz = self._get_tz()
        utc_dt = pytz.utc.localize(dt)
        return utc_dt.astimezone(tz)
792907
def stringToDateTime(s, tzinfo=None):
    
    try:
        year = int(s[0:4])
        month = int(s[4:6])
        day = int(s[6:8])
        hour = int(s[9:11])
        minute = int(s[11:13])
        second = int(s[13:15])
        if len(s) > 15:
            if s[15] == 'Z':
                tzinfo = getTzid('UTC')
    except:
        raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
    year = year and year or 2000
    if tzinfo is not None and hasattr(tzinfo,'localize'):  # PyTZ case
        return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
    return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
120529
def _get_fields(self, table_name, **kwargs):
        """"""
        ret = {}
        query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name))
        fields = self._query(query_str, **kwargs)
        #pout.v([dict(d) for d in fields])

        query_str = 'PRAGMA foreign_key_list({})'.format(self._normalize_table_name(table_name))
        fks = {f["from"]: f for f in self._query(query_str, **kwargs)}
        #pout.v([dict(d) for d in fks.values()])

        pg_types = {
            "INTEGER": int,
            "BIGINT": long,
            "DOUBLE PRECISION": float,
            "FLOAT": float,
            "REAL": float,
            "NUMERIC": decimal.Decimal,
            "BOOLEAN": bool,
            "DATE": datetime.date,
            "TIMESTAMP": datetime.datetime,
            "CHARACTER": str,
            "VARCHAR": str,
            "TEXT": str,
            "BLOB": bytearray,
        }

        # the rows we can set: field_type, name, field_required, min_size, max_size,
        #   size, unique, pk, <foreign key info>
        # These keys will roughly correspond with schema.Field
        # TODO -- we could actually use "type" to get the size because SQLite returns
        # a value like VARCHAR[32]
        for row in fields:
            field = {
                "name": row["name"],
                "field_required": bool(row["notnull"]) or bool(row["pk"]),
                "pk": bool(row["pk"]),
            }

            for tname, ty in pg_types.items():
                if row["type"].startswith(tname):
                    field["field_type"] = ty
                    break

            if field["pk"] and field["field_type"] is int:
                # we compensate for SQLite internally setting pk to int
                field["field_type"] = long

            if row["name"] in fks:
                field["schema_table_name"] = fks[row["name"]]["table"]
                field["ref_table_name"] = fks[row["name"]]["table"]

            ret[field["name"]] = field

        return ret
3315
public ZonedDateTime getInternalZonedDateTime(ColumnInformation columnInfo, Class clazz,
      TimeZone timeZone) throws SQLException {
    if (lastValueWasNull()) {
      return null;
    }
    if (length == 0) {
      lastValueNull |= BIT_LAST_FIELD_NULL;
      return null;
    }

    switch (columnInfo.getColumnType().getSqlType()) {
      case Types.TIMESTAMP:

        int year = ((buf[pos] & 0xff) | (buf[pos + 1] & 0xff) << 8);
        int month = buf[pos + 2];
        int day = buf[pos + 3];
        int hour = 0;
        int minutes = 0;
        int seconds = 0;
        int microseconds = 0;

        if (length > 4) {
          hour = buf[pos + 4];
          minutes = buf[pos + 5];
          seconds = buf[pos + 6];

          if (length > 7) {
            microseconds = ((buf[pos + 7] & 0xff)
                + ((buf[pos + 8] & 0xff) << 8)
                + ((buf[pos + 9] & 0xff) << 16)
                + ((buf[pos + 10] & 0xff) << 24));
          }
        }

        return ZonedDateTime
            .of(year, month, day, hour, minutes, seconds, microseconds * 1000, timeZone.toZoneId());

      case Types.VARCHAR:
      case Types.LONGVARCHAR:
      case Types.CHAR:

        //string conversion
        String raw = new String(buf, pos, length, StandardCharsets.UTF_8);
        if (raw.startsWith("0000-00-00 00:00:00")) {
          return null;
        }
        try {
          return ZonedDateTime.parse(raw, TEXT_ZONED_DATE_TIME);
        } catch (DateTimeParseException dateParserEx) {
          throw new SQLException(raw
              + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" "
              + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')");
        }

      default:
        throw new SQLException(
            "Cannot read " + clazz.getName() + " using a " + columnInfo.getColumnType()
                .getJavaTypeName() + " field");
    }

  }
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