Set UTC timezone on a datetime object.

    A naive datetime is assumed to be in UTC TZ.
350493
def utc_dt(dt):
    
    if not dt.tzinfo:
        return pytz.utc.localize(dt)
    return dt.astimezone(pytz.utc)
996980
def datetime_to_timezone(date, tz="UTC"):
    
    if not date.tzinfo:
        date = date.replace(tzinfo=timezone(get_timezone()))
    return date.astimezone(timezone(tz))
615281
def ensure_timezone(dt, tz=None):
    
    if dt.tzinfo is None:
        return dt.replace(tzinfo=tz or tzlocal())
    else:
        return dt
250428
def to_naive_utc(dtime):
    
    if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None:
        return dtime

    dtime_utc = dtime.astimezone(pytz.UTC)
    dtime_naive = dtime_utc.replace(tzinfo=None)
    return dtime_naive
1048626
public synchronized static void setDefault(TimeZone timeZone) {
        defaultTimeZone = timeZone != null ? (TimeZone) timeZone.clone() : null;
    }
851014
def _date_bin_set_datetime(new_date):
    '''
    
    '''
    cmd = ['date']

    # if there is a timezone in the datetime object use that offset
    # This will modify the new_date to be the equivalent time in UTC
    if new_date.utcoffset() is not None:
        new_date = new_date - new_date.utcoffset()
        new_date = new_date.replace(tzinfo=_FixedOffset(0))
        cmd.append('-u')

    # the date can be set in the following format:
    # Note that setting the time with a resolution of seconds
    # is not a posix feature, so we will attempt it and if it
    # fails we will try again only using posix features

    # date MMDDhhmm[[CC]YY[.ss]]
    non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}"
                 .format(*new_date.timetuple()))
    non_posix_cmd = cmd + [non_posix]

    ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False)
    if ret_non_posix['retcode'] != 0:
        # We will now try the command again following posix
        # date MMDDhhmm[[CC]YY]
        posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple())
        posix_cmd = cmd + [posix]

        ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False)
        if ret_posix['retcode'] != 0:
            # if both fail it's likely an invalid date string
            # so we will give back the error from the first attempt
            msg = 'date failed: {0}'.format(ret_non_posix['stderr'])
            raise CommandExecutionError(msg)
    return True
754548
def timezone(self, tz):
        
        self.data['resolving'].update(
            timezone=tz,
            time_show_zone=True)
1338363
def astimezone(self, tzinfo):
    
    # Assert we are not a naive datetime object
    assert self.tzinfo is not None

    tzinfo = _tzinfome(tzinfo)

    d = self.asdatetime(naive=False).astimezone(tzinfo)
    return type(self)(d)
545676
def date_utc(self) -> datetime:
        """"""
        return datetime.utcfromtimestamp(self._node["date"] if "date" in self._node else self._node["taken_at_timestamp"])
821212
def ensure_timezone(dateTime,timeZone=None):
    '''
    
    '''

    if is_aware(dateTime) and not getattr(settings,'USE_TZ',False):
        return make_naive(dateTime,timezone=timeZone)
    if is_naive(dateTime) and getattr(settings,'USE_TZ',False):
        return make_aware(dateTime,timezone=timeZone)
    # If neither condition is met, then we can return what was passed
    return dateTime
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
1289613
def _safe_timezone(obj):
    # type: (Union[str, int, float, _datetime.tzinfo]) -> _Timezone
    
    if isinstance(obj, _Timezone):
        return obj

    if obj is None or obj == "local":
        return local_timezone()

    if isinstance(obj, (int, float)):
        obj = int(obj * 60 * 60)
    elif isinstance(obj, _datetime.tzinfo):
        # pytz
        if hasattr(obj, "localize"):
            obj = obj.zone
        else:
            offset = obj.utcoffset(None)

            if offset is None:
                offset = _datetime.timedelta(0)

            obj = int(offset.total_seconds())

    return timezone(obj)
270655
def _build_date_time_time_zone(self, date_time):
        
        timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None
        return {
            self._cc('dateTime'): date_time.strftime('%Y-%m-%dT%H:%M:%S'),
            self._cc('timeZone'): get_windows_tz(timezone or self.protocol.timezone)
        }
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)
47079
def to_utc(self, dt):
        """"""
        if dt.tzinfo is None:
            return dt.replace(tzinfo=self.utc)
        return dt.astimezone(self.utc)
705829
def instance(
    dt, tz=UTC  # type: _datetime.datetime  # type: Union[str, _Timezone, None]
):  # type: (...) -> DateTime
    
    if not isinstance(dt, _datetime.datetime):
        raise ValueError("instance() only accepts datetime objects.")

    if isinstance(dt, DateTime):
        return dt

    tz = dt.tzinfo or tz

    # Checking for pytz/tzinfo
    if isinstance(tz, _datetime.tzinfo) and not isinstance(tz, _Timezone):
        # pytz
        if hasattr(tz, "localize") and tz.zone:
            tz = tz.zone
        else:
            # We have no sure way to figure out
            # the timezone name, we fallback
            # on a fixed offset
            tz = tz.utcoffset(dt).total_seconds() / 3600

    return datetime(
        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tz=tz
    )
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;        
    }