• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python dates.format_time函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.dates.format_time函数的典型用法代码示例。如果您正苦于以下问题:Python format_time函数的具体用法?Python format_time怎么用?Python format_time使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了format_time函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: datetimeformat

def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    tzinfo = timezone(settings.TIME_ZONE)
    tzvalue = tzinfo.localize(value)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                                    tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (tzvalue.isoformat(), formatted))
开发者ID:tantek,项目名称:kuma,代码行数:35,代码来源:helpers.py


示例2: datetimeformat

def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    request = context.get('request')

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if 'timezone' not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = request.user.get_profile().timezone or \
                                 default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session['timezone'] = convert_tzinfo
    else:
        convert_tzinfo = request.session['timezone']

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u'Today at %s') % format_time(
                convert_value, format='short', tzinfo=convert_tzinfo,
                locale=locale)
        else:
            formatted = format_datetime(convert_value, format='short',
                tzinfo=convert_tzinfo, locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(convert_value, format='long',
            tzinfo=convert_tzinfo, locale=locale)
    elif format == 'date':
        formatted = format_date(convert_value, locale=locale)
    elif format == 'time':
        formatted = format_time(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (convert_value.isoformat(), formatted))
开发者ID:bajubullet,项目名称:kitsune,代码行数:60,代码来源:helpers.py


示例3: test_no_inherit_metazone_formatting

def test_no_inherit_metazone_formatting():
    # See: https://github.com/python-babel/babel/issues/428
    tz = pytz.timezone('America/Los_Angeles')
    t = tz.localize(datetime(2016, 1, 6, 7))
    assert dates.format_time(t, format='long', locale='en_US') == "7:00:00 AM PST"
    assert dates.format_time(t, format='long', locale='en_GB') == "07:00:00 Pacific Standard Time"
    assert dates.get_timezone_name(t, width='short', locale='en_US') == "PST"
    assert dates.get_timezone_name(t, width='short', locale='en_GB') == "Pacific Standard Time"
开发者ID:python-babel,项目名称:babel,代码行数:8,代码来源:test_dates.py


示例4: datetimeformat

def datetimeformat(context, value, format="shortdatetime"):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError("Unexpected value {value} passed to datetimeformat".format(value=value))

    request = context.get("request")

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if "timezone" not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = Profile.objects.get(user=request.user).timezone or default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session["timezone"] = convert_tzinfo
    else:
        convert_tzinfo = request.session["timezone"]

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == "shortdatetime":
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u"Today at %s") % format_time(
                convert_value, format="short", tzinfo=convert_tzinfo, locale=locale
            )
        else:
            formatted = format_datetime(convert_value, format="short", tzinfo=convert_tzinfo, locale=locale)
    elif format == "longdatetime":
        formatted = format_datetime(convert_value, format="long", tzinfo=convert_tzinfo, locale=locale)
    elif format == "date":
        formatted = format_date(convert_value, locale=locale)
    elif format == "time":
        formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale)
    elif format == "datetime":
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % (convert_value.isoformat(), formatted))
开发者ID:rivaxel,项目名称:kitsune,代码行数:54,代码来源:helpers.py


示例5: test_format_time

    def test_format_time(self):
        import datetime
        from babel.dates import format_time
        from babel.core import UnknownLocaleError

        api = self.make()
        first = datetime.time(23, 59)
        self.assertEqual(api.format_time(first), format_time(first, format="medium", locale="en"))
        self.assertEqual(api.format_time(first, format="short"), format_time(first, format="short", locale="en"))
        api.locale_name = "unknown"
        self.assertRaises(UnknownLocaleError, api.format_time, first)
开发者ID:mujinjun,项目名称:Kotti,代码行数:11,代码来源:test_util_views.py


示例6: datetimeformat

def datetimeformat(context, value, format='shortdatetime', output='html'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        if isinstance(value, datetime.date):
            # Turn a date into a datetime
            value = datetime.datetime.combine(value,
                                              datetime.datetime.min.time())
        else:
            # Expecting datetime value
            raise ValueError

    default_tz = timezone(settings.TIME_ZONE)
    tzvalue = default_tz.localize(value)

    user = context['request'].user
    try:
        profile = user.get_profile()
        if user.is_authenticated() and profile.timezone:
            user_tz = profile.timezone
            tzvalue = user_tz.normalize(tzvalue.astimezone(user_tz))
    except AttributeError:
        pass

    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    if output == 'json':
        return formatted
    return jinja2.Markup('<time datetime="%s">%s</time>' %
                         (tzvalue.isoformat(), formatted))
开发者ID:FrankBian,项目名称:kuma,代码行数:52,代码来源:helpers.py


示例7: test_format_time

 def test_format_time(self, db_session):
     import datetime
     from babel.dates import format_time
     from babel.core import UnknownLocaleError
     api = self.make()
     first = datetime.time(23, 59)
     assert (
         api.format_time(first) ==
         format_time(first, format='medium', locale='en'))
     assert (
         api.format_time(first, fmt='short') ==
         format_time(first, format='short', locale='en'))
     api.locale_name = 'unknown'
     with raises(UnknownLocaleError):
         api.format_time(first)
开发者ID:disko,项目名称:Kotti,代码行数:15,代码来源:test_util_views.py


示例8: format_time

def format_time(time=None, format=None, locale=None, timezone=None,
    rebase=True):
    """Returns a time formatted according to the given pattern and following
    the current locale and timezone.

    :param time:
        A ``time`` or ``datetime`` object. If None, the current
        time in UTC is used.
    :param format:
        The format to be returned. Valid values are "short", "medium",
        "long", "full" or a custom date/time pattern. Example outputs:

        - short:  4:36 PM
        - medium: 4:36:05 PM
        - long:   4:36:05 PM +0000
        - full:   4:36:05 PM World (GMT) Time

    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :param timezone:
        The timezone name from the Olson database, e.g.: ``America/Chicago``.
        If not set, uses the default returned by :func:`get_timezone`.
    :param rebase:
        If True, converts the time to the currently loaded timezone.
    :returns:
        A formatted time in unicode.
    """
    format = _get_format('time', format)
    locale = locale or get_locale()

    kwargs = {}
    if rebase:
        kwargs['tzinfo'] = get_timezone(timezone)

    return dates.format_time(time, format, locale=locale, **kwargs)
开发者ID:Hubble1,项目名称:eventgrinder,代码行数:35,代码来源:i18n.py


示例9: format_time

    def format_time(self, t=None, format='medium'):
        """Return a time formatted according to the given pattern

        >>> t = datetime.time(15, 30)
        >>> Locale('en', 'US').format_time(t)
        u'3:30:00 PM'
        >>> Locale('de', 'DE').format_time(t, format='short')
        u'15:30'

        If you don't want to use the locale default formats, you can specify a
        custom time pattern:

        >>> Locale('en').format_time(t, "hh 'o''clock' a")
        u"03 o'clock PM"

        In:
          - ``t`` --  ``time`` or ``datetime`` object; if `None`, the current time in UTC is used
          - ``format`` -- 'full', 'long', 'medium', or 'short', or a custom date/time pattern

        Returns:
          - the formatted time string
        """
        if isinstance(t, datetime.time):
            d = datetime.datetime.now()
            t = d.replace(hour=t.hour, minute=t.minute, second=t.second)

        if isinstance(t, datetime.datetime):
            t = self.to_utc(t)

        return dates.format_time(t, format, locale=self, tzinfo=self.tzinfo)
开发者ID:nagareproject,项目名称:core,代码行数:30,代码来源:i18n.py


示例10: pretty_time

def pretty_time(dt):
    display_tz = pytz.timezone(c.liveupdate_event.timezone)
    today = datetime.datetime.now(display_tz).date()
    date = dt.astimezone(display_tz).date()

    if date == today:
        return format_time(
            time=dt,
            tzinfo=display_tz,
            format="HH:mm z",
            locale=c.locale,
        )
    elif today - date < datetime.timedelta(days=365):
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM HH:mm z",
            locale=c.locale,
        )
    else:
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM YYYY HH:mm z",
            locale=c.locale,
        )
开发者ID:Web5design,项目名称:reddit-plugin-liveupdate,代码行数:26,代码来源:utils.py


示例11: test_format_time

 def test_format_time(self):
     import datetime
     from babel.dates import format_time
     from babel.core import UnknownLocaleError
     api = self._make()
     first = datetime.time(23, 59)
     self.assertEqual(
         api.format_time(first),
         format_time(first, format='medium', locale='en'),
     )
     self.assertEqual(
         api.format_time(first, format='short'),
         format_time(first, format='short', locale='en'),
     )
     api.locale_name = 'unknown'
     self.assertRaises(UnknownLocaleError, api.format_time, first)
开发者ID:djpnewton,项目名称:Kotti,代码行数:16,代码来源:tests.py


示例12: __mod__

 def __mod__(self, fmt):
     try:
         return format_time(self.time,
                            fmt,
                            locale=text_type(pilot.context.get('.locale', 'en_US')))
     except:
         raise ValueError("'{}' is not a valid time format string".format(fmt))
开发者ID:chrmorais,项目名称:moya,代码行数:7,代码来源:expressiontime.py


示例13: test_time

 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_time(value_test, locale=u'en_US')
     value_returned = datetimeformat(self.context, value_test,
                                     format='time')
     eq_(pq(value_returned)('time').text(), value_expected)
开发者ID:VoodooLab,项目名称:kuma,代码行数:7,代码来源:test_helpers.py


示例14: test_smoke_dates

def test_smoke_dates(locale):
    locale = Locale.parse(locale)
    instant = datetime.now()
    for width in ("full", "long", "medium", "short"):
        assert dates.format_date(instant, format=width, locale=locale)
        assert dates.format_datetime(instant, format=width, locale=locale)
        assert dates.format_time(instant, format=width, locale=locale)
开发者ID:Mabusto,项目名称:babel,代码行数:7,代码来源:test_smoke.py


示例15: asString

 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
开发者ID:ahilles107,项目名称:Superdesk,代码行数:25,代码来源:text_conversion.py


示例16: format_time

    def format_time(self, time=None, format=None, rebase=True):
        """Returns a time formatted according to the given pattern and
        following the current locale and timezone.

        :param time:
            A ``time`` or ``datetime`` object. If None, the current
            time in UTC is used.
        :param format:
            The format to be returned. Valid values are "short", "medium",
            "long", "full" or a custom date/time pattern. Example outputs:

            - short:  4:36 PM
            - medium: 4:36:05 PM
            - long:   4:36:05 PM +0000
            - full:   4:36:05 PM World (GMT) Time

        :param rebase:
            If True, converts the time to the current :attr:`timezone`.
        :returns:
            A formatted time in unicode.
        """
        format = self._get_format('time', format)

        kwargs = {}
        if rebase:
            kwargs['tzinfo'] = self.tzinfo

        return dates.format_time(time, format, locale=self.locale, **kwargs)
开发者ID:404minds,项目名称:quiz-forest,代码行数:28,代码来源:i18n.py


示例17: localize_timestamp

def localize_timestamp(timestamp, user):
    try:
        user_timezone = dates.get_timezone(user.timezone)
    except LookupError:
        user_timezone = dates.get_timezone('Etc/UTC')

    try:
        user_locale = Locale(user.locale)
    except core.UnknownLocaleError:
        user_locale = Locale('en')

    # Do our best to find a valid locale
    try:
        user_locale.date_formats
    except IOError:  # An IOError will be raised if locale's casing is incorrect, e.g. de_de vs. de_DE
        # Attempt to fix the locale, e.g. de_de -> de_DE
        try:
            user_locale = Locale(fix_locale(user.locale))
            user_locale.date_formats
        except (core.UnknownLocaleError, IOError):
            user_locale = Locale('en')

    formatted_date = dates.format_date(timestamp, format='full', locale=user_locale)
    formatted_time = dates.format_time(timestamp, format='short', tzinfo=user_timezone, locale=user_locale)

    return u'{time} on {date}'.format(time=formatted_time, date=formatted_date)
开发者ID:CenterForOpenScience,项目名称:osf.io,代码行数:26,代码来源:emails.py


示例18: test_time

 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_time(value_test, locale='en_US')
     value_returned = datetimeformat(self.context, value_test,
                                     format='time',
                                     output='json')
     assert value_expected == value_returned
开发者ID:Elchi3,项目名称:kuma,代码行数:8,代码来源:test_helpers.py


示例19: format_time

def format_time(t, request):
	if t is None:
		return ''
	if not isinstance(t, (datetime, time)):
		return t

	l = get_locale(request)
	return dates.format_time(t, locale=l)
开发者ID:OpenCIOC,项目名称:featuretracker,代码行数:8,代码来源:request.py


示例20: test_today

 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     value_returned = unicode(datetimeformat(self.context, date_today))
     value_expected = 'Today at %s' % format_time(date_today,
                                                  format='short',
                                                  locale=u'en_US')
     eq_(pq(value_returned)('time').text(), value_expected)
开发者ID:VoodooLab,项目名称:kuma,代码行数:8,代码来源:test_helpers.py



注:本文中的babel.dates.format_time函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python dates.format_timedelta函数代码示例发布时间:2022-05-24
下一篇:
Python dates.format_datetime函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap