本文整理汇总了Python中babel.dates.format_datetime函数的典型用法代码示例。如果您正苦于以下问题:Python format_datetime函数的具体用法?Python format_datetime怎么用?Python format_datetime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_datetime函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: pretty_time
def pretty_time(dt, allow_relative=True):
ago = datetime.datetime.now(pytz.UTC) - dt
if allow_relative and ago < datetime.timedelta(hours=24):
return template_helpers.simplified_timesince(dt)
elif dt.date() == datetime.datetime.now(pytz.UTC).date():
return format_datetime(
datetime=dt,
tzinfo=pytz.UTC,
format="HH:mm",
locale=c.locale,
)
elif ago < datetime.timedelta(days=365):
return format_datetime(
datetime=dt,
tzinfo=pytz.UTC,
format="dd MMM HH:mm",
locale=c.locale,
)
else:
return format_datetime(
datetime=dt,
tzinfo=pytz.UTC,
format="dd MMM YYYY HH:mm",
locale=c.locale,
)
开发者ID:KeyserSosa,项目名称:reddit-plugin-liveupdate,代码行数:26,代码来源:utils.py
示例2: getRSSFeed
def getRSSFeed(items):
# XML Header
rssContent = '<?xml version="1.0" encoding="iso-8859-1"?>\r\n'
rssContent += '<rss version="2.0">\r\n'
rssContent += "\t<channel>\r\n"
rssContent += "\t\t<title>XDM RSS Feed - AutoGet-It</title>\r\n"
rssContent += "\t\t<link>http://xdm.lad1337.de</link>\r\n"
rssContent += "\t\t<description>RSS feed generated by XDM to download.</description>\r\n"
rssContent += "\t\t<lastBuildDate>%s</lastBuildDate>\r\n" % format_datetime(
datetime.datetime.now(), "E, d MMM yyyy HH:mm:ss", locale="en_US"
)
rssContent += "\t\t<generator>XDM RSS downloader Plugin</generator>\r\n\r\n"
# XML Content
for item in items:
rssContent += "\t\t<item>\r\n"
rssContent += "\t\t\t<title>%s</title>\r\n" % item["title"]
rssContent += "\t\t\t<link>%s</link>\r\n" % item["link"]
rssContent += "\t\t\t<guid>%s</guid>\r\n" % item["guid"]
rssContent += "\t\t\t<pubDate>%s</pubDate>\r\n" % format_datetime(
item["pubDate"], "E, d MMM yyyy HH:mm:ss", locale="en_US"
)
rssContent += "\t\t</item>\r\n"
# XML Footer
rssContent += "\t</channel>\r\n</rss>\r\n"
return rssContent
开发者ID:nonontb,项目名称:XDM-French-Touch,代码行数:27,代码来源:RSS.py
示例3: 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
示例4: 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
示例5: 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
示例6: _get_mime_headers
def _get_mime_headers(self):
headers = []
headers.append(('Project-Id-Version',
'%s %s' % (self.project, self.version)))
headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
headers.append(('POT-Creation-Date',
format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
locale='en')))
if isinstance(self.revision_date, (datetime, time_) + number_types):
headers.append(('PO-Revision-Date',
format_datetime(self.revision_date,
'yyyy-MM-dd HH:mmZ', locale='en')))
else:
headers.append(('PO-Revision-Date', self.revision_date))
headers.append(('Last-Translator', self.last_translator))
if (self.locale is not None) and ('LANGUAGE' in self.language_team):
headers.append(('Language-Team',
self.language_team.replace('LANGUAGE',
str(self.locale))))
else:
headers.append(('Language-Team', self.language_team))
if self.locale is not None:
headers.append(('Plural-Forms', self.plural_forms))
headers.append(('MIME-Version', '1.0'))
headers.append(('Content-Type',
'text/plain; charset=%s' % self.charset))
headers.append(('Content-Transfer-Encoding', '8bit'))
headers.append(('Generated-By', 'Babel %s\n' % VERSION))
return headers
开发者ID:A-Tran,项目名称:Indecisive,代码行数:29,代码来源:catalog.py
示例7: export2json
def export2json(export):
# TODO: This doesn't actually work, I can't figure out how to get
# the corect data out of redis
if export.status != 'complete':
data = redis.hgetall(export.redis_key)
else:
data = {}
log.debug('info: {}'.format(str(data)))
count = len(export.contents)
return {
'id': export.id,
'title': localizer.pluralize(
_(u'Export containing ${count} item'),
_(u'Export containing ${count} items'),
count, 'occams', mapping={'count': count}),
'name': export.name,
'status': export.status,
'use_choice_labels': export.use_choice_labels,
'expand_collections': export.expand_collections,
'contents': sorted(export.contents, key=lambda v: v['title']),
'count': data.get('count'),
'total': data.get('total'),
'file_size': (naturalsize(export.file_size)
if export.file_size else None),
'download_url': request.route_path('studies.export_download',
export=export.id),
'delete_url': request.route_path('studies.export',
export=export.id),
'create_date': format_datetime(export.create_date, locale=locale),
'expire_date': format_datetime(export.expire_date, locale=locale)
}
开发者ID:m-martinez,项目名称:occams,代码行数:31,代码来源:export.py
示例8: _get_mime_headers
def _get_mime_headers(self):
headers = []
headers.append(('Project-Id-Version',
'%s %s' % (self.project, self.version)))
headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
headers.append(('POT-Creation-Date',
format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
locale='en')))
if self.locale is None:
headers.append(('PO-Revision-Date', 'YEAR-MO-DA HO:MI+ZONE'))
headers.append(('Last-Translator', 'FULL NAME <[email protected]>'))
headers.append(('Language-Team', 'LANGUAGE <[email protected]>'))
else:
headers.append(('PO-Revision-Date',
format_datetime(self.revision_date,
'yyyy-MM-dd HH:mmZ', locale='en')))
headers.append(('Last-Translator', self.last_translator))
headers.append(('Language-Team',
self.language_team.replace('LANGUAGE',
str(self.locale))))
headers.append(('Plural-Forms', self.plural_forms))
headers.append(('MIME-Version', '1.0'))
headers.append(('Content-Type',
'text/plain; charset=%s' % self.charset))
headers.append(('Content-Transfer-Encoding', '8bit'))
headers.append(('Generated-By', 'Babel %s\n' % VERSION))
return headers
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:27,代码来源:catalog.py
示例9: formatDateTime
def formatDateTime(dateTime, showWeek=False, format=None, locale=None):
week = ""
locale = str(locale or currentLocale())
if showWeek:
week = "EEEE "
if not format:
return format_datetime(dateTime, week+'d/M/yyyy H:mm', locale=locale).encode('utf-8')
else:
return format_datetime(dateTime, format, locale=locale).encode('utf-8')
开发者ID:aninhalacerda,项目名称:indico,代码行数:9,代码来源:utils.py
示例10: 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
示例11: test_format_datetime
def test_format_datetime():
dt = datetime(2007, 4, 1, 15, 30)
assert (dates.format_datetime(dt, locale='en_US') ==
u'Apr 1, 2007, 3:30:00 PM')
full = dates.format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'),
locale='fr_FR')
assert full == (u'dimanche 1 avril 2007 à 17:30:00 heure '
u'd\u2019\xe9t\xe9 d\u2019Europe centrale')
custom = dates.format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
tzinfo=timezone('US/Eastern'), locale='en')
assert custom == u'2007.04.01 AD at 11:30:00 EDT'
开发者ID:python-babel,项目名称:babel,代码行数:12,代码来源:test_dates.py
示例12: test_format_current_moment
def test_format_current_moment(monkeypatch):
import datetime as datetime_module
frozen_instant = datetime.utcnow()
class frozen_datetime(datetime):
@classmethod
def utcnow(cls):
return frozen_instant
# Freeze time! Well, some of it anyway.
monkeypatch.setattr(datetime_module, "datetime", frozen_datetime)
assert dates.format_datetime(locale="en_US") == dates.format_datetime(frozen_instant, locale="en_US")
开发者ID:shubh1m,项目名称:babel,代码行数:12,代码来源:test_dates.py
示例13: matches_datetime_format_for_team
def matches_datetime_format_for_team(value, tz):
utcnow = datetime.datetime.utcnow()
if value.year != utcnow.year:
return dates.format_datetime(value,
"MMM d',' yyyy 'at' h':'mm a zzz",
locale='en_US',
tzinfo=pytz.timezone(tz))
return dates.format_datetime(value,
"EEE',' MMM d 'at' h':'mm a zzz",
locale='en_US',
tzinfo=pytz.timezone(tz))
开发者ID:kenrobbins,项目名称:tardyrush,代码行数:12,代码来源:filters.py
示例14: 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
示例15: format_datetime_local
def format_datetime_local(datetime, format="medium"):
"""Format the output of a datetime object to a localized string"""
from babel.dates import format_datetime
from django.conf import settings
from django.utils.translation.trans_real import to_locale
# See http://babel.pocoo.org/docs/api/dates/#date-and-time-formatting
# for customizing the output format.
try:
result = format_datetime(datetime, format, locale=to_locale(settings.LANGUAGE_CODE))
except ValueError:
result = format_datetime(datetime, format, locale="en_US")
return result
开发者ID:gboone,项目名称:relate,代码行数:14,代码来源:utils.py
示例16: test_format_datetime
def test_format_datetime(self):
import datetime
from babel.dates import format_datetime
from babel.core import UnknownLocaleError
api = self.make()
first = datetime.datetime(2012, 1, 1, 0)
self.assertEqual(api.format_datetime(first), format_datetime(first, format="medium", locale="en"))
self.assertEqual(
api.format_datetime(time.mktime(first.timetuple())), format_datetime(first, format="medium", locale="en")
)
self.assertEqual(
api.format_datetime(first, format="short"), format_datetime(first, format="short", locale="en")
)
api.locale_name = "unknown"
self.assertRaises(UnknownLocaleError, api.format_datetime, first)
开发者ID:mujinjun,项目名称:Kotti,代码行数:16,代码来源:test_util_views.py
示例17: test_default
def test_default(self):
"""Expects shortdatetime."""
value_test = datetime.fromordinal(733900)
value_expected = format_datetime(value_test, format='short',
locale=u'en_US')
value_returned = datetimeformat(self.context, value_test)
eq_(pq(value_returned)('time').text(), value_expected)
开发者ID:VoodooLab,项目名称:kuma,代码行数:7,代码来源:test_helpers.py
示例18: 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
示例19: format_datetime
def format_datetime(self, datetime=None, format=None, rebase=True):
"""Returns a date and time formatted according to the given pattern
and following the current locale and timezone.
:param datetime:
A ``datetime`` object. If None, the current date and 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: 11/10/09 4:36 PM
- medium: Nov 10, 2009 4:36:05 PM
- long: November 10, 2009 4:36:05 PM +0000
- full: Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time
:param rebase:
If True, converts the datetime to the current :attr:`timezone`.
:returns:
A formatted date and time in unicode.
"""
format = self._get_format('datetime', format)
kwargs = {}
if rebase:
kwargs['tzinfo'] = self.tzinfo
return dates.format_datetime(datetime, format, locale=self.locale,
**kwargs)
开发者ID:404minds,项目名称:quiz-forest,代码行数:29,代码来源:i18n.py
示例20: format_tz
def format_tz(pool, cr, uid, dt, tz=False, format=False, context=None):
context = dict(context or {})
if tz:
context['tz'] = tz or pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] or "UTC"
timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)
ts = openerp.osv.fields.datetime.context_timestamp(cr, uid, timestamp, context)
# Babel allows to format datetime in a specific language without change locale
# So month 1 = January in English, and janvier in French
# Be aware that the default value for format is 'medium', instead of 'short'
# medium: Jan 5, 2016, 10:20:31 PM | 5 janv. 2016 22:20:31
# short: 1/5/16, 10:20 PM | 5/01/16 22:20
if context.get('use_babel'):
# Formatting available here : http://babel.pocoo.org/en/latest/dates.html#date-fields
from babel.dates import format_datetime
return format_datetime(ts, format or 'medium', locale=context.get("lang") or 'en_US')
if format:
return ts.strftime(format)
else:
lang = context.get("lang")
lang_params = {}
if lang:
res_lang = pool.get('res.lang')
ids = res_lang.search(cr, uid, [("code", "=", lang)])
if ids:
lang_params = res_lang.read(cr, uid, ids[0], ["date_format", "time_format"])
format_date = lang_params.get("date_format", '%B-%d-%Y')
format_time = lang_params.get("time_format", '%I-%M %p')
fdate = ts.strftime(format_date).decode('utf-8')
ftime = ts.strftime(format_time)
return "%s %s%s" % (fdate, ftime, (' (%s)' % tz) if tz else '')
开发者ID:c0ns0le,项目名称:oscom,代码行数:34,代码来源:mail_template.py
注:本文中的babel.dates.format_datetime函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论