Python datetime.time 模块,tzinfo() 实例源码

我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用datetime.time.tzinfo()

项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def get_timezone(zone=None):
    """Looks up a timezone by name and returns it.  The timezone object
    returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
    can be used with all of the functions of Babel that operate with dates.

    If a timezone is not known a :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def get_timezone(zone=None):
    """Looks up a timezone by name and returns it.  The timezone object
    returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
    can be used with all of the functions of Babel that operate with dates.

    If a timezone is not known a :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone)
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def get_timezone(zone=None):
    """Looks up a timezone by name and returns it.  The timezone object
    returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
    can be used with all of the functions of Babel that operate with dates.

    If a timezone is not known a :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone)
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def get_timezone(zone=None):
    """Looks up a timezone by name and returns it.  The timezone object
    returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
    can be used with all of the functions of Babel that operate with dates.

    If a timezone is not known a :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def tzinfo(self):
        """
        Alias for tz attribute
        """
        return self.tz
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _timezone(self):
        """ Comparable timezone both for pytz / dateutil"""
        return tslib.get_timezone(self.tzinfo)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _has_same_tz(self, other):
        zzone = self._timezone

        # vzone sholdn't be None if value is non-datetime like
        if isinstance(other, np.datetime64):
            # convert to Timestamp as np.datetime64 doesn't have tz attr
            other = Timestamp(other)
        vzone = tslib.get_timezone(getattr(other, 'tzinfo', '__no_tz__'))
        return zzone == vzone
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def indexer_at_time(self, time, asof=False):
        """
        Select values at particular time of day (e.g. 9:30AM)

        Parameters
        ----------
        time : datetime.time or string

        Returns
        -------
        values_at_time : TimeSeries
        """
        from dateutil.parser import parse

        if asof:
            raise NotImplementedError("'asof' argument is not supported")

        if isinstance(time, compat.string_types):
            time = parse(time).time()

        if time.tzinfo:
            # TODO
            raise NotImplementedError("argument 'time' with timezone info is "
                                      "not supported")

        time_micros = self._get_time_micros()
        micros = _time_to_micros(time)
        return (micros == time_micros).nonzero()[0]
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _generate_regular_range(start, end, periods, offset):
    if isinstance(offset, Tick):
        stride = offset.nanos
        if periods is None:
            b = Timestamp(start).value
            # cannot just use e = Timestamp(end) + 1 because arange breaks when
            # stride is too large, see GH10887
            e = b + (Timestamp(end).value - b) // stride * stride + stride // 2
            # end.tz == start.tz by this point due to _generate implementation
            tz = start.tz
        elif start is not None:
            b = Timestamp(start).value
            e = b + np.int64(periods) * stride
            tz = start.tz
        elif end is not None:
            e = Timestamp(end).value + stride
            b = e - np.int64(periods) * stride
            tz = end.tz
        else:
            raise ValueError("at least 'start' or 'end' should be specified "
                             "if a 'period' is given.")

        data = np.arange(b, e, stride, dtype=np.int64)
        data = DatetimeIndex._simple_new(data, None, tz=tz)
    else:
        if isinstance(start, Timestamp):
            start = start.to_pydatetime()

        if isinstance(end, Timestamp):
            end = end.to_pydatetime()

        xdr = generate_range(start=start, end=end,
                             periods=periods, offset=offset)

        dates = list(xdr)
        # utc = len(dates) > 0 and dates[0].tzinfo is not None
        data = tools.to_datetime(dates)

    return data
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale)
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    if dt is None:
        dt = datetime.utcnow()
    else:
        dt = dt.replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
    """Return the timezone associated with the given `datetime` object formatted
    as string indicating the offset from GMT.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT+00:00'

    >>> tz = get_timezone('America/Los_Angeles')
    >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT-08:00'
    >>> get_timezone_gmt(dt, 'short', locale='en')
    u'-0800'

    The long format depends on the locale, for example in France the acronym
    UTC string is used instead of GMT:

    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
    u'UTC-08:00'

    .. versionadded:: 0.9

    :param datetime: the ``datetime`` object; if `None`, the current date and
                     time in UTC is used
    :param width: either "long" or "short"
    :param locale: the `Locale` object, or a locale string
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, integer_types):
        datetime = datetime_.utcfromtimestamp(datetime).time()
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    locale = Locale.parse(locale)

    offset = datetime.tzinfo.utcoffset(datetime)
    seconds = offset.days * 24 * 60 * 60 + offset.seconds
    hours, seconds = divmod(seconds, 3600)
    if width == 'short':
        pattern = u'%+03d%02d'
    else:
        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
    return pattern % (hours, seconds // 60)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 04, 01, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 17:30:00 heure avanc\xe9e d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, number_types):
        datetime = datetime_.utcfromtimestamp(datetime)
    elif isinstance(datetime, time):
        datetime = datetime_.combine(date.today(), datetime)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'): # pytz
            datetime = tzinfo.normalize(datetime)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    if dt is None:
        dt = datetime.utcnow()
    else:
        dt = dt.replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    )
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
    """Return the timezone associated with the given `datetime` object formatted
    as string indicating the offset from GMT.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT+00:00'

    >>> tz = get_timezone('America/Los_Angeles')
    >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT-07:00'
    >>> get_timezone_gmt(dt, 'short', locale='en')
    u'-0700'

    The long format depends on the locale, for example in France the acronym
    UTC string is used instead of GMT:

    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
    u'UTC-07:00'

    .. versionadded:: 0.9

    :param datetime: the ``datetime`` object; if `None`, the current date and
                     time in UTC is used
    :param width: either "long" or "short"
    :param locale: the `Locale` object, or a locale string
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, integer_types):
        datetime = datetime_.utcfromtimestamp(datetime).time()
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    locale = Locale.parse(locale)

    offset = datetime.tzinfo.utcoffset(datetime)
    seconds = offset.days * 24 * 60 * 60 + offset.seconds
    hours, seconds = divmod(seconds, 3600)
    if width == 'short':
        pattern = u'%+03d%02d'
    else:
        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
    return pattern % (hours, seconds // 60)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, number_types):
        datetime = datetime_.utcfromtimestamp(datetime)
    elif isinstance(datetime, time):
        datetime = datetime_.combine(date.today(), datetime)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'): # pytz
            datetime = tzinfo.normalize(datetime)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale)
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    if dt is None:
        dt = datetime.utcnow()
    else:
        dt = dt.replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    )
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
    """Return the timezone associated with the given `datetime` object formatted
    as string indicating the offset from GMT.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT+00:00'

    >>> tz = get_timezone('America/Los_Angeles')
    >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT-07:00'
    >>> get_timezone_gmt(dt, 'short', locale='en')
    u'-0700'

    The long format depends on the locale, for example in France the acronym
    UTC string is used instead of GMT:

    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
    u'UTC-07:00'

    .. versionadded:: 0.9

    :param datetime: the ``datetime`` object; if `None`, the current date and
                     time in UTC is used
    :param width: either "long" or "short"
    :param locale: the `Locale` object, or a locale string
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, integer_types):
        datetime = datetime_.utcfromtimestamp(datetime).time()
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    locale = Locale.parse(locale)

    offset = datetime.tzinfo.utcoffset(datetime)
    seconds = offset.days * 24 * 60 * 60 + offset.seconds
    hours, seconds = divmod(seconds, 3600)
    if width == 'short':
        pattern = u'%+03d%02d'
    else:
        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
    return pattern % (hours, seconds // 60)
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 04, 01, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 17:30:00 heure avanc\xe9e d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, number_types):
        datetime = datetime_.utcfromtimestamp(datetime)
    elif isinstance(datetime, time):
        datetime = datetime_.combine(date.today(), datetime)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'): # pytz
            datetime = tzinfo.normalize(datetime)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale)
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    if dt is None:
        dt = datetime.utcnow()
    else:
        dt = dt.replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    )
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
    """Return the timezone associated with the given `datetime` object formatted
    as string indicating the offset from GMT.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT+00:00'

    >>> tz = get_timezone('America/Los_Angeles')
    >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT-07:00'
    >>> get_timezone_gmt(dt, 'short', locale='en')
    u'-0700'

    The long format depends on the locale, for example in France the acronym
    UTC string is used instead of GMT:

    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
    u'UTC-07:00'

    .. versionadded:: 0.9

    :param datetime: the ``datetime`` object; if `None`, the current date and
                     time in UTC is used
    :param width: either "long" or "short"
    :param locale: the `Locale` object, or a locale string
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, integer_types):
        datetime = datetime_.utcfromtimestamp(datetime).time()
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    locale = Locale.parse(locale)

    offset = datetime.tzinfo.utcoffset(datetime)
    seconds = offset.days * 24 * 60 * 60 + offset.seconds
    hours, seconds = divmod(seconds, 3600)
    if width == 'short':
        pattern = u'%+03d%02d'
    else:
        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
    return pattern % (hours, seconds // 60)
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 04, 01, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 17:30:00 heure avanc\xe9e d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, number_types):
        datetime = datetime_.utcfromtimestamp(datetime)
    elif isinstance(datetime, time):
        datetime = datetime_.combine(date.today(), datetime)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'): # pytz
            datetime = tzinfo.normalize(datetime)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale)