本文整理汇总了Python中DateTime.DateTime.strftime方法的典型用法代码示例。如果您正苦于以下问题:Python DateTime.strftime方法的具体用法?Python DateTime.strftime怎么用?Python DateTime.strftime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTime.DateTime
的用法示例。
在下文中一共展示了DateTime.strftime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: datehandler
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def datehandler(value):
# TODO: we might want to handle datetime and time as well;
# check the enfold.solr implementation
if value is None or value is '':
raise AttributeError
if isinstance(value, str) and not value.endswith('Z'):
try:
value = DateTime(value)
except SyntaxError:
raise AttributeError
if isinstance(value, DateTime):
v = value.toZone('UTC')
value = '%04d-%02d-%02dT%02d:%02d:%06.3fZ' % (
v.year(), v.month(), v.day(), v.hour(), v.minute(), v.second()
)
elif isinstance(value, datetime):
# Convert a timezone aware timetuple to a non timezone aware time
# tuple representing utc time. Does nothing if object is not
# timezone aware
value = datetime(*value.utctimetuple()[:7])
value = '%s.%03dZ' % (
value.strftime('%Y-%m-%dT%H:%M:%S'),
value.microsecond % 1000
)
elif isinstance(value, date):
value = '%s.000Z' % value.strftime('%Y-%m-%dT%H:%M:%S')
return value
示例2: get_hover_events
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def get_hover_events(self, date):
""" """
ret = []
date = date.split('/')
events = self.get_events(date[0], date[1], date[2])
for e in events:
title = e.get('title', '')
location = e.get('location', '')
s_date = DateTime(e.get('startdate', None))
e_date = DateTime(e.get('enddate', None))
startdate = s_date.strftime('%d.%m')
enddate = e_date.strftime('%d.%m')
if startdate or enddate:
ret.append('[')
if startdate:
ret.append(startdate)
if enddate and e_date != s_date:
if startdate:
ret.append(' - %s' % enddate)
else:
ret.append(enddate)
if startdate or enddate:
ret.append(']')
if title:
ret.append(' - %s' % title)
if location:
ret.append(' - %s' % location)
ret.append('\n')
ret.pop(-1)
return ''.join(ret)
示例3: postChange
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def postChange(self):
"""
Change id and filename, fixing extension if necessary
"""
logger.info("postChange: newId and notifyParent")
if self.subtype is not None:
now = DateTime()
self.setId("%s-%s" % (self.subtype, now.strftime("%Y-%m-%d-%H-%M")))
# Deal with filename
filefield = self.getField("file")
filename = filefield.getFilename(self)
basename, extension = os.path.splitext(filename)
# Guess a correct extension according to MimeType
mimetypes_registry = getToolByName(self, "mimetypes_registry", None)
mtype = mimetypes_registry.lookup(filefield.getContentType(self))
try:
suggestedext = mtype[0].extensions[0]
except:
pass
logger.info("suggesting %s" % suggestedext)
if len(extension) <= 0:
extension = ".%s" % suggestedext
logger.info("Filename is %s, extension %s" % (filename, extension))
filefield.setFilename(self, "%s-%s%s" % (self.subtype, now.strftime("%Y%m%d"), extension))
parent = aq_parent(aq_inner(self))
parent.set_current_draft(self.id)
parent.reindexObject()
示例4: _getNextId
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def _getNextId(self):
now=DateTime()
id = 'Collab.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')
count = 0
while hasattr(self.aq_base, id):
id = 'Collab.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')+'.'+str(count)
count = count + 1
return id
示例5: _createId
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def _createId(self):
now=DateTime()
id = 'Patch.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')
count = 0
while hasattr(self.aq_base, id):
id = 'Patch.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')+'.'+str(count)
count = count + 1
return id
示例6: date
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def date(self, item):
dt = DateTime(item.Date())
if (item.portal_type in [u'Compromisso',
u'Event']):
dt = DateTime(item.start_date)
if self.data.show_time:
return dt.strftime('%d/%m/%Y | %H:%M')
else:
return dt.strftime('%d/%m/%Y')
示例7: noticias
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def noticias(self, items):
noticias = OrderedDict()
locale.setlocale(locale.LC_TIME, "pt_BR")
for i in items:
data = DateTime(i.Date())
month = unicode(data.strftime('%b'), 'iso-8859-1') + '/' + data.strftime('%d')
title = i.Title() + ':' + '/'.join(i.getObject().getPhysicalPath())
noticias.setdefault(month, []).append(title)
return noticias
示例8: testStrftimeUnicode
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def testStrftimeUnicode(self):
if IS_PYPY:
# Using Non-Ascii characters for strftime doesn't work in PyPy
# https://bitbucket.org/pypy/pypy/issues/2161/pypy3-strftime-does-not-accept-unicode
return
dt = DateTime('2002-05-02T08:00:00+00:00')
uchar = b'\xc3\xa0'.decode('utf-8')
ok = dt.strftime('Le %d/%m/%Y a %Hh%M').replace('a', uchar)
ustr = b'Le %d/%m/%Y \xc3\xa0 %Hh%M'.decode('utf-8')
self.assertEqual(dt.strftime(ustr), ok)
示例9: update
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def update(self):
super(HeaderTimeViewlet, self).update()
date = DateTime()
self.day = date.day()
self.month = _pl(monthname_msgid(int(date.strftime('%m'))),
default=safe_unicode(date.Month()))
self.dayname = _pl(weekdayname_msgid(int(date.strftime('%w'))),
default=safe_unicode(date.DayOfWeek()))
self.datetime = self.toLocalizedTime(date, long_format=True)
示例10: getIntervalListBetweenDates
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def getIntervalListBetweenDates(from_date=None, to_date=None,
keys={'year':1, 'month':1, 'week' : 1, 'day':1}):
"""
Return the list of years, months and days (if each is equal to 1 in keys)
between the both given dates including the current one.
If one of the given dates is None, the date used is the current time.
"""
# key -> format dict
format_dict = {'year':'%Y',
'month':'%Y-%m',
'week':'%Y-%V',
'day':'%Y-%m-%d',
}
if from_date is None:
from_date = DateTime()
if to_date is None:
to_date = DateTime()
if from_date - to_date > 0:
from_date, to_date = to_date, from_date
to_inverse = 1
else:
to_inverse = 0
diff_value_dict = {}
for current_key in ('year', 'month', 'week', 'day'):
if keys.get(current_key, None):
new_date = from_date
while new_date <= to_date:
if current_key == 'day':
new_strftime = new_date.ISO()
new_strftime = new_strftime[:new_strftime.index(' ')]
diff_value_dict.setdefault(current_key, []).append(new_strftime)
else:
diff_value_dict.setdefault(current_key,
[]).append(new_date.strftime(format_dict[current_key]))
if current_key == "week":
new_date = addToDate(new_date, to_add={'day':7})
else:
new_date = addToDate(new_date, to_add={current_key:1})
if to_date.strftime(format_dict[current_key]) not in\
diff_value_dict[current_key]:
diff_value_dict.setdefault(current_key,
[]).append(to_date.strftime(format_dict[current_key]))
returned_value_dict = {}
for key, value in diff_value_dict.iteritems():
if to_inverse:
value.reverse()
returned_value_dict[key] = value
else:
returned_value_dict[key] = value
return returned_value_dict
示例11: _get_ims
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def _get_ims(self, since=None, till=None, uid=None):
"""Returns list of instant messages"""
result = []
purl = self.purl()
mtool = getToolByName(self.context, 'portal_membership')
storage = getUtility(IPubSubStorage)
escaper = getUtility(INodeEscaper)
convert = getToolByName(self, 'portal_transforms').convert
# go over recent messages
for item in storage.itemsFromNodes(['people'], start=0,
count=DEFAULT_ITEMS_NUM):
# TODO: handle comments
if item.get('parent'):
continue
datetime = DateTime(item['updated']).toZone('GMT')
# TODO: handle till argument
if since and since >= datetime:
# we've got too old entry, break from the loop
break
fullname = author = item['author']
if author:
author = escaper.unescape(author)
member = mtool.getMemberById(author)
if member:
fullname = member.getProperty('fullname', None) or author
else:
fullname = author
# strip down html code from message body
body = safe_unicode(item['content']).encode('utf-8')
body = safe_unicode(convert('html_to_text', body).getData())
result.append({
'uid': item['id'],
'type': 'im',
'image': {'url': mtool.getPersonalPortrait(author
).absolute_url(), 'alt': _(safe_unicode(author))},
'url': '%s/@@pubsub-feed?node=%s' % (purl, author),
'title': _(safe_unicode(fullname)),
'date': datetime.strftime('%b %d, %Y'),
'time': datetime.strftime('%I:%M'),
'datetime': datetime,
'replies_num': 0,
'can_reply': True,
'body': body
})
return result
示例12: _createFolderStructure
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def _createFolderStructure(self, folder, structure='ymd', date=None):
""" Create a folder structure and then return our innermost folder
"""
if not date:
date = DateTime()
dateFormat = structure
if '%B' in dateFormat:
translation = getToolByName(self.context, 'translation_service')
PLMF = MessageFactory('plonelocales')
dateFormat = dateFormat.replace('%B', '%m')
date = date.strftime(dateFormat)
folderStructure = [str(p) for p in date.split('/')]
index = dateFormat.split('/').index('%m')
month_msgid = PLMF(translation.month_msgid(folderStructure[index]))
try:
target_language = i18n.negotiate(self.context.REQUEST)
except:
target_language = None
transale_month = translate(month_msgid, target_language=target_language)
folderStructure[index] = transale_month
else:
date = date.strftime(dateFormat)
folderStructure = [str(p) for p in date.split('/')]
container = self.element.container
language = folder.Language()
normalizer = getUtility(IIDNormalizer)
portal_workflow = getToolByName(self.context, 'portal_workflow')
pw = portal_workflow.doActionFor
# We run IRuleExecutor here to make sure other rules will be
# executed for the newly created folders
executor = IRuleExecutor(self.context, None)
for fId in folderStructure:
fTitle = fId
fId = normalizer.normalize(fId)
if not fId in folder.objectIds():
_createObjectByType(container, folder, id=normalizer.normalize(fId),
title=fTitle, description=fTitle)
folder = folder[fId]
pw(folder, 'publish')
# this makes happy multilang sites
folder.setLanguage(language)
event = ObjectAddedEvent(folder, aq_parent(folder), fId)
if executor is not None:
executor(event)
else:
folder = folder[fId]
return folder
示例13: addLink
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def addLink(self, target, title, category, strength):
"""Add a link object"""
now=DateTime()
id = 'Link.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')
count = 0
while id in self.objectIds():
id = 'Link.'+now.strftime('%Y-%m-%d')+'.'+now.strftime('%M%S')+'.'+str(count)
count = count + 1
self._setObject(id, ExtendedLink(id), suppress_events=True)
l = getattr(self, id)
l.edit(self.absolute_url(), target, title, category, strength)
return l
示例14: _get_zmails
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def _get_zmails(self, since=None, till=None, uid=None):
"""Returns list of recent zimbra emails."""
purl = self.purl()
# get zimbra settings
mtool = getToolByName(self.context, 'portal_membership')
member = mtool.getAuthenticatedMember()
username = member.getProperty('zimbra_username', '')
password = member.getProperty('zimbra_password', '')
if not (username and password):
return []
# make zimbra soap query to get list of recent emails
try:
zimbra = getUtility(IZimbraUtil).get_client(username=username,
password=password)
mails = zimbra.get_emails(folder='inbox', limit=DEFAULT_ITEMS_NUM,
types='message')
except Exception:
logException(_(u"Error during fetching zimbra mails"),
context=self.context, logger=logger)
return []
zurl = getZimbraUrl(self.context)
result = []
for mail in mails:
# TODO: handle till argument
datetime = DateTime(int(mail['date']) / 1000).toZone('GMT')
if since and since >= datetime:
# we've got too old entry, break from the loop
break
result.append({
'uid': mail['id'],
'type': 'zm',
'image': {
'url': '%s/add_content_area/metabox_icon_email.png' %
purl, 'alt': _(u"MAIL")},
'url': '%s/zimbra/h/search?st=conversation&id=%s' \
'&action=view&cid=%s' % (zurl, mail['id'],
mail['cid']),
'title': _(u"MAIL"),
'date': datetime.strftime('%b %d, %Y'),
'time': datetime.strftime('%I:%M'),
'datetime': datetime,
'replies_num': 0,
'can_reply': True,
'body': mail['subject']
})
return result
示例15: toCalendarLocalizedTime
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import strftime [as 别名]
def toCalendarLocalizedTime(self, time):
"""Convert a date in the calendar date format"""
time = DateTime(time.strftime("%Y-%m-%d"))
mapping = {}
formatstring = translate('date_format_long', 'monet.calendar.extensions', mapping,
self.request, default="${A} ${B} ${d} ${Y}")
# get the format elements used in the formatstring
formatelements = _interp_regex.findall(formatstring)
# reformat the ${foo} to foo
formatelements = [el[2:-1] for el in formatelements]
# add used elements to mapping
elements = [e for e in formatelements if e in datetime_formatvariables]
# add weekday name, abbr. weekday name, month name, abbr month name
week_included = True
month_included = True
name_elements = [e for e in formatelements if e in name_formatvariables]
if not ('a' in name_elements or 'A' in name_elements):
week_included = False
if not ('b' in name_elements or 'B' in name_elements):
month_included = False
for key in elements:
mapping[key]=time.strftime('%'+key)
if week_included:
weekday = int(time.strftime('%w')) # weekday, sunday = 0
if 'a' in name_elements:
mapping['a']=weekdayname_msgid_abbr(weekday)
if 'A' in name_elements:
mapping['A']=weekdayname_msgid(weekday)
if month_included:
monthday = int(time.strftime('%m')) # month, january = 1
if 'b' in name_elements:
mapping['b']=monthname_msgid_abbr(monthday)
if 'B' in name_elements:
mapping['B']=monthname_msgid(monthday)
# translate translateable elements
for key in name_elements:
mapping[key] = translate(mapping[key], 'plonelocales', context=self.request, default=mapping[key])
# translate the time string
return translate('date_format_long', 'monet.calendar.extensions', mapping,
self.request, default="${A} ${B} ${d} ${Y}")