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