本文整理汇总了Python中babel.dates.format_time函数的典型用法代码示例。如果您正苦于以下问题:Python format_time函数的具体用法?Python format_time怎么用?Python format_time使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_time函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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))
示例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"
示例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))
示例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)
示例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))
示例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)
示例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)
示例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)
示例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,
)
示例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)
示例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))
示例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)
示例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)
示例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)