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

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

项目:pongr    作者:wseaton    | 项目源码 | 文件源码
def matches():
    singles = pd.read_sql('select * from game where deleted = 0', con=engine)
    doubles = pd.read_sql('select * from doubles_game where deleted = 0', con=engine)

    tz = pytz.timezone('America/New_York')

    for frame in [singles, doubles]:

        frame['timestamp'] = frame['timestamp'].apply(datetime.utcfromtimestamp)
        frame['timestamp'] = frame['timestamp'].apply(datetime.replace, tzinfo=tz)
        frame['timestamp'] = frame['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S %Z')

    singles = singles.to_dict('records')
    doubles = doubles.to_dict('records')

    return render_template('gamelog.html', singles_games=singles, doubles_games=doubles)
项目:pongr    作者:wseaton    | 项目源码 | 文件源码
def push_new_doubles_ratings(con=None):
    """
    recalculates doubles ratings and pushes them to the database
    """
    games = pd.read_sql('select * from doubles_game where deleted = 0', con=con)

    ratingdf = calculate_doubles_ratings(games)
    ratingdf = (ratingdf.reset_index().rename(columns={'index':'alias'})
                .drop('level_0', axis=1))

    ratingdf.to_sql('doubles_ratings', con=con, if_exists='replace', index=False)

    team_ratingdf = calculate_team_ratings(games)
    team_ratingdf = (team_ratingdf.reset_index().rename(columns={'index': 'team'})
                .drop('level_0', axis=1))

    team_ratingdf.to_sql('team_doubles_ratings', con=con, if_exists='replace', index=False)
项目: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)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1
项目: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)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1
项目:pongr    作者:wseaton    | 项目源码 | 文件源码
def push_new_ratings(con=None):
    """
    recalculates player ratings and pushes them to the database
    """
    games = pd.read_sql('select * from game where deleted = 0', con=con)

    ratingdf = calculate_ratings(games)
    ratingdf = (ratingdf.reset_index().rename(columns={'index':'alias'})
                .drop('level_0', axis=1))

    ratingdf.to_sql('ratings', con=con, if_exists='replace', index=False)
项目: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)
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1
项目:itchatmp    作者:littlecodersh    | 项目源码 | 文件源码
def maintain_thread(self, firstCallResult=None):
        ''' thread to update token and
        register next update event into event loop '''
        r = firstCallResult or self._syncTokenFunction()
        if not r:
            self.core.ioLoop.call_later(
                (datetime.replace(datetime.now() + timedelta(days=1), 
                hour=0, minute=5, second=0) - datetime.now()).seconds,
                self.maintain_access_token, None)
        else:
            self.core.ioLoop.call_later(r['expires_in'] - 30,
                self.maintain_access_token, None)
项目:itchatmp    作者:littlecodersh    | 项目源码 | 文件源码
def set_server_list(self):
        self._serverList = []
        serverList, fetchTime = self.core.atStorage.get_server_list()
        if fetchTime < time.mktime(datetime.replace(datetime.now(),
            hour=0, minute=0, second=0).timetuple()):
            r = self._serverIpFn()
            if not r:
                logger.debug(r)
            else:
                self._serverList = r.get('ip_list', [])
                self.core.atStorage.store_server_list(self._serverList, time.time())
        else:
            self._serverList = serverList
项目:itchatmp    作者:littlecodersh    | 项目源码 | 文件源码
def filter_request(self, request):
        if self._serverList is None:
            t = threading.Thread(target=self.set_server_list)
            t.setDaemon = True
            t.start()
            def clear_server_list():
                self._serverList = None
            self.core.ioLoop.call_later(
                (datetime.replace(datetime.now() + timedelta(days=1), 
                hour=0, minute=5, second=0) - datetime.now()).seconds,
                clear_server_list)
        if not self._serverList:
            logger.debug('Server list is loading, so ignore verifying once.')
            return True
        return request.remote_ip in self._serverList
项目: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)
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def to_utc(datetime):
    """Convert a datetime object to UTC and drop tzinfo.  This is the
    opposite operation to :func:`to_user_timezone`.
    """
    if datetime.tzinfo is None:
        datetime = get_timezone().localize(datetime)
    return datetime.astimezone(UTC).replace(tzinfo=None)
项目: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)
项目:pongr    作者:wseaton    | 项目源码 | 文件源码
def ratings():
    s = '''
    select
        first_name,
        last_name,
        alias,
        rating,
        sigma,
        trueskill
    from ratings
    left join player using (alias)
    order by 3 desc
    '''

    s_team = '''
        select
            player1,
            player2,
            rating,
            sigma,
            trueskill
        from team_doubles_ratings
        --left join player using (alias)
        order by 3 desc
        '''

    s_rating_df = pd.read_sql(s, con=engine)
    d_rating_df = pd.read_sql(s.replace('ratings', 'doubles_ratings'), con=engine)
    t_rating_df = pd.read_sql(s_team, con=engine)


    chart = dist_plot(s_rating_df)

    singles_rating_df_4_template = s_rating_df.copy()

    s_rating_df = s_rating_df.to_dict('records')
    d_rating_df = d_rating_df.to_dict('records')
    t_rating_df = t_rating_df.to_dict('records')
    # top is for the data table as records, bottom is TrueSkill objects
    s_r_dict = rating_df_to_dict(singles_rating_df_4_template)

    rdo = OrderedDict(sorted(s_r_dict.items(), key=lambda x: x[1].mu, reverse=True))

    percent_df = pd.DataFrame()

    for pair in list(itertools.combinations_with_replacement(rdo, 2)):
        prob = win_probability(rdo[pair[0]], rdo[pair[1]])
        percent_df.loc[pair[0], pair[1]] = prob
        percent_df.loc[pair[1], pair[0]] = 1 - prob

    matrix = win_probability_matrix(percent_df)

    return render_template('ratings.html', singles_ratings=s_rating_df,
                           doubles_ratings=d_rating_df, team_df=t_rating_df,
                           dist=chart, matrix=matrix)
项目: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)