本文整理汇总了Python中trac.util.datefmt.to_datetime函数的典型用法代码示例。如果您正苦于以下问题:Python to_datetime函数的具体用法?Python to_datetime怎么用?Python to_datetime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_datetime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_search_results
def get_search_results(self, req, keywords, filters):
self.log.debug("PHPDOCBUG: kw=%s f=%s" % (keywords, filters))
if not 'phpdoc' in filters:
return
# We have to search for the raw bytes...
keywords = [k.encode(self.encoding) for k in keywords]
for doc in os.listdir(self.base_path):
# Search in documentation directories
path = os.path.join(self.base_path, doc)
path = os.path.join(path, self.html_output)
self.log.debug("looking in doc (%s) dir: %s:" % (doc, path))
if os.path.isdir(path):
index = os.path.join(path, 'search.idx')
if os.path.exists(index):
creation = os.path.getctime(index)
for result in self._search_in_documentation(doc, keywords):
result['url'] = req.href.phpdoc(doc) + '/' \
+ result['url']
yield result['url'], result['name'], to_datetime(creation), \
'phpdoc', None
# Search in common documentation directory
index = os.path.join(self.base_path, self.html_output)
index = os.path.join(index, 'search.idx')
self.log.debug("looking in doc (%s) search.idx: %s:" % (doc, index))
if os.path.exists(index):
creation = os.path.getctime(index)
for result in self._search_in_documentation('', keywords):
result['url'] = req.href.phpdoc() + '/' + \
result['url']
yield result['url'], result['name'], to_datetime(creation), 'phpdoc', \
None
示例2: expand_macro
def expand_macro(self, formatter, name, content):
env = formatter.env
req = formatter.req
if not 'VOTE_VIEW' in req.perm:
return
# Simplify function calls.
format_author = partial(Chrome(self.env).format_author, req)
if not content:
args = []
compact = None
kw = {}
top = 5
else:
args, kw = parse_args(content)
compact = 'compact' in args and True
top = as_int(kw.get('top'), 5, min=0)
if name == 'LastVoted':
lst = tag.ul()
for i in self.get_votes(req, top=top):
resource = Resource(i[0], i[1])
# Anotate who and when.
voted = ('by %s at %s'
% (format_author(i[3]),
format_datetime(to_datetime(i[4]))))
lst(tag.li(tag.a(
get_resource_description(env, resource, compact and
'compact' or 'default'),
href=get_resource_url(env, resource, formatter.href),
title=(compact and '%+i %s' % (i[2], voted) or None)),
(not compact and Markup(' %s %s' % (tag.b('%+i' % i[2]),
voted)) or '')))
return lst
elif name == 'TopVoted':
realm = kw.get('realm')
lst = tag.ul()
for i in self.get_top_voted(req, realm=realm, top=top):
if 'up-only' in args and i[2] < 1:
break
resource = Resource(i[0], i[1])
lst(tag.li(tag.a(
get_resource_description(env, resource, compact and
'compact' or 'default'),
href=get_resource_url(env, resource, formatter.href),
title=(compact and '%+i' % i[2] or None)),
(not compact and ' (%+i)' % i[2] or '')))
return lst
elif name == 'VoteList':
lst = tag.ul()
resource = resource_from_path(env, req.path_info)
for i in self.get_votes(req, resource, top=top):
vote = ('at %s' % format_datetime(to_datetime(i[4])))
lst(tag.li(
compact and format_author(i[3]) or
Markup(u'%s by %s %s' % (tag.b('%+i' % i[2]),
tag(format_author(i[3])), vote)),
title=(compact and '%+i %s' % (i[2], vote) or None)))
return lst
示例3: _parse_build
def _parse_build(self, res):
data = json.loads(res.read())
if not 'results' in data or not (type(data['results']) == int):
status = "running"
else:
status = "successful" if data['results'] == 0 else "failed"
build = dict({
'builder': data['builderName'],
'status': status,
'start' : to_datetime(int(data['times'][0]), utc),
'num': data['number'],
})
if len(data['times']) > 1 and type(data['times'][1]) == float:
build['finish'] = to_datetime(int(data['times'][1]), utc)
for prop in data['properties']:
if prop[0] == 'got_revision' and prop[1] != "":
build["rev"] = prop[1]
break
if status == "failed":
build['error'] = ', '.join(data['text'])
try:
for step in data['steps']:
if "results" in step and step["results"][0] == 2:
build['error_log'] = step['logs'][0][1]
break
except (IndexError, KeyError):
pass
return build
示例4: _process_add
def _process_add(self, req, ticket):
if req.method == "POST" and self._validate_add(req):
if req.args.get('reminder_type') == 'interval':
time = clear_time(to_datetime(None))
delta = _time_intervals[req.args.get('unit')](req.args.get('interval'))
time += delta
time = to_utimestamp(time)
else:
time = to_utimestamp(parse_date(req.args.get('date')))
origin = to_utimestamp(to_datetime(None))
self.env.db_transaction("""
INSERT INTO ticketreminder
(ticket, time, author, origin, reminded, description)
VALUES (%s, %s, %s, %s, 0, %s)
""", (ticket.id, time, get_reporter_id(req, 'author'),
origin, req.args.get('description')))
add_notice(req, "Reminder has been added.")
req.redirect(get_resource_url(self.env, ticket.resource, req.href) + "#reminders")
add_script(req, 'ticketreminder/js/ticketreminder.js')
data = {
'ticket': ticket,
'date_hint': get_date_format_hint(),
}
return ("ticket_reminder_add.html", data, None)
示例5: _fetch_fields
def _fetch_fields(self, version=0):
""" Returns a dict with field/value combinations for the content
of a specific version of a blog post, or last/current version if
version is 0.
Returns emtpy dict if no such post or post/version exists. """
self.versions = self.get_versions()
if not self.versions or (version and not version in self.versions):
# No blog post with the name exists
return {}
version = version or self.versions[-1]
cnx = self.env.get_db_cnx()
cursor = cnx.cursor()
cursor.execute("SELECT title, body, publish_time, version_time, "
"version_comment, version_author, author, categories "
"FROM fullblog_posts "
"WHERE name=%s AND version=%s",
(self.name, version) )
fields = {}
for row in cursor:
fields['version'] = version
fields['title'] = row[0]
fields['body'] = row[1]
fields['publish_time'] = to_datetime(row[2], utc)
fields['version_time'] = to_datetime(row[3], utc)
fields['version_comment'] = row[4]
fields['version_author'] = row[5]
fields['author'] = row[6]
fields['categories'] = row[7]
fields['category_list'] = set(_parse_categories(row[7]))
return fields
示例6: test_to_datetime_microsecond_negative_timestamps
def test_to_datetime_microsecond_negative_timestamps(self):
# Work around issue1646728 in Python 2.4
expected = datetime.datetime.fromtimestamp(-2345, datefmt.localtz) - datetime.timedelta(seconds=0.678912)
self.assertEqual(datefmt.to_datetime(-2345678912).microsecond, 321088) # 1000000 - 678912
self.assertEqual(datefmt.to_datetime(-2345678912), expected)
self.assertEqual(datefmt.to_datetime(-2345678912L), expected)
self.assertEqual(datefmt.to_datetime(-2345678912.0), expected)
示例7: get_work_log
def get_work_log(self, pid, username=None, mode='all'):
db = self.env.get_read_db()
cursor = db.cursor()
if mode == 'user':
assert username is not None
cursor.execute('SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, t.summary, t.status, wl.comment '
'FROM work_log wl '
'JOIN ticket t ON wl.ticket=t.id '
'WHERE t.project_id=%s AND wl.worker=%s '
'ORDER BY wl.lastchange DESC',
(pid, username))
elif mode == 'latest':
cursor.execute('''
SELECT worker, starttime, endtime, ticket, summary, status, comment
FROM (
SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, wl.comment, wl.lastchange,
MAX(wl.lastchange) OVER (PARTITION BY wl.worker) latest,
t.summary, t.status
FROM work_log wl
JOIN ticket t ON wl.ticket=t.id AND project_id=%s
) wll
WHERE lastchange=latest
ORDER BY lastchange DESC, worker
''', (pid,))
else:
cursor.execute('SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, t.summary, t.status, wl.comment '
'FROM work_log wl '
'JOIN ticket t ON wl.ticket=t.id '
'WHERE t.project_id=%s '
'ORDER BY wl.lastchange DESC, wl.worker',
(pid,))
rv = []
for user,starttime,endtime,ticket,summary,status,comment in cursor:
started = to_datetime(starttime)
if endtime != 0:
finished = to_datetime(endtime)
delta = 'Worked for %s (between %s and %s)' % (
pretty_timedelta(started, finished),
format_datetime(started), format_datetime(finished))
else:
finished = 0
delta = 'Started %s ago (%s)' % (
pretty_timedelta(started),
format_datetime(started))
rv.append({'user': user,
'starttime': started,
'endtime': finished,
'delta': delta,
'ticket': ticket,
'summary': summary,
'status': status,
'comment': comment})
return rv
示例8: format_date
def format_date(self,content,propname,d,force_date=False,tzinfo=None):
if type(d) == datetime.datetime and force_date == False:
tz = tzinfo or localtz
t = to_datetime(d, tzinfo).astimezone(tz)
content.write("%s:%s\r\n" % (propname,t.strftime("%Y%m%dT%H%M%S")))
elif type(d) == datetime.datetime and force_date == True:
tz = tzinfo or localtz
t = to_datetime(d, tzinfo).astimezone(tz)
content.write("%s;VALUE=DATE:%s\r\n" % (propname,t.strftime("%Y%m%d")))
else:
content.write("%s;VALUE=DATE:%s\r\n" % (propname,d.strftime("%Y%m%d")))
示例9: better_parse_date
def better_parse_date(text, tzinfo=None):
tzinfo = tzinfo or localtz
if text == "now": # TODO: today, yesterday, etc.
return datetime.now(utc)
tm = None
text = text.strip()
# normalize ISO time
match = datefmt._ISO_8601_RE.match(text)
if match:
try:
g = match.groups()
years = g[0]
months = g[1] or "01"
days = g[2] or "01"
hours, minutes, seconds = [x or "00" for x in g[3:6]]
z, tzsign, tzhours, tzminutes = g[6:10]
if z:
tz = timedelta(hours=int(tzhours or "0"), minutes=int(tzminutes or "0")).seconds / 60
if tz == 0:
tzinfo = utc
else:
tzinfo = datefmt.FixedOffset(tzsign == "-" and -tz or tz, "%s%s:%s" % (tzsign, tzhours, tzminutes))
tm = strptime("%s " * 6 % (years, months, days, hours, minutes, seconds), "%Y %m %d %H %M %S ")
except ValueError:
pass
else:
for format in ["%x %X", "%x, %X", "%X %x", "%X, %x", "%x", "%c", "%b %d, %Y"]:
try:
tm = strptime(text, format)
break
except ValueError:
continue
if tm == None:
hint = datefmt.get_date_format_hint()
raise TracError(
'"%s" is an invalid date, or the date format ' 'is not known. Try "%s" instead.' % (text, hint),
"Invalid Date",
)
if not hasattr(tzinfo, "localize"):
# This is a tzinfo define by trac which don't have to deal with dst
dt = datetime(*(tm[0:6] + (0, tzinfo)))
else:
# We need to detect daylight saving correctly - see #...
dt = tzinfo.localize(datetime(*tm[0:6]))
# Make sure we can convert it to a timestamp and back - fromtimestamp()
# may raise ValueError if larger than platform C localtime() or gmtime()
try:
datefmt.to_datetime(datefmt.to_timestamp(dt), tzinfo)
except ValueError:
raise TracError(
'The date "%s" is outside valid range. ' "Try a date closer to present time." % (text,), "Invalid Date"
)
return dt
示例10: set_status_dt
def set_status_dt(env,ticket_id,new_status=None,new_time=None,db=None):
order_lst = env.config.getlist('querychart', 'order')
order =[]
custom_fields = {}
for m in order_lst:
ms = m.split(':')
if len(ms) >= 2:
order.append(ms[0])
custom_fields[ms[0]] = ':'.join(ms[1:])
else:
order.append(m)
if not db:
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute("SELECT newvalue,time,ticket ,field from ticket_change where ticket=%s"
" and field=%s"
" order by time",(ticket_id,'status'))
history=[(row[0],to_datetime(row[1])) for row in cursor]
if new_status:
history.append((new_status,new_time))
result ={}
for new_status,time in history:
#set date by priority of 'order'
#if status date (higher priority than next status) is none, set date to higher priority.
#and set none to lower priority status date.
if not new_status in order:
continue
idx = order.index(new_status)
formated_date = format_date(to_datetime(time))
for m_idx in range(len(order)-1, -1, -1):
if not order[m_idx] in custom_fields:
continue
m_field = custom_fields[order[m_idx]]
if not m_field in result:
result[m_field] = None
if idx==m_idx:
result[m_field]=formated_date
elif idx<m_idx:
result[m_field]=None
else:
if result[m_field]==None:
result[m_field]=formated_date
else:
formated_date=result[m_field]
return result
示例11: format_cell
def format_cell(self, name, value):
value_type = self.determine_type(name)
if value_type == 'time':
return to_datetime(value).strftime('%Y-%m-%d')
if value_type == 'date':
return str(to_datetime(value));
if type(value) == StringType:
return str(value)
if type(value) == UnicodeType:
return value.encode('ascii', 'xmlcharrefreplace')
else:
return value
示例12: get_timeline_events
def get_timeline_events(self, req, start, stop, filters, pid, syllabus_id):
if pid is None:
return
is_multi = isinstance(pid, (list, tuple))
if is_multi:
# TODO:
return
# Worklog changes
show_starts = 'workstart' in filters
show_stops = 'workstop' in filters
if show_starts or show_stops:
add_stylesheet(req, "worklog/worklogplugin.css")
ts_start = to_timestamp(start)
ts_stop = to_timestamp(stop)
ticket_realm = Resource('ticket')
db = self.env.get_read_db()
cursor = db.cursor()
cursor.execute("""
SELECT wl.worker,wl.ticket,wl.time,wl.starttime,wl.comment,wl.kind,t.summary,t.status,t.resolution,t.type
FROM (
SELECT worker, ticket, starttime AS time, starttime, comment, 'start' AS kind
FROM work_log
UNION
SELECT worker, ticket, endtime AS time, starttime, comment, 'stop' AS kind
FROM work_log
) AS wl
JOIN ticket t ON t.id = wl.ticket AND project_id=%s AND wl.time>=%s AND wl.time<=%s
ORDER BY wl.time""", (pid, ts_start, ts_stop))
for worker,tid,ts,ts_start,comment,kind,summary,status,resolution,type in cursor:
ticket = ticket_realm(id=tid)
time = to_datetime(ts)
started = None
if kind == 'start':
if not show_starts:
continue
yield ('workstart', pid, time, worker, (ticket,summary,status,resolution,type, started, ""))
else:
if not show_stops:
continue
started = to_datetime(ts_start)
if comment:
comment = "(Time spent: %s)\n\n%s" % (pretty_timedelta(started, time), comment)
else:
comment = '(Time spent: %s)' % pretty_timedelta(started, time)
yield ('workstop', pid, time, worker, (ticket,summary,status,resolution,type, started, comment))
示例13: extend
def extend(self):
'''
Check for all Changetimes and Return the highest Changetime as
Int
'''
timemax = to_datetime( 0, utc )
timenow = to_datetime( datetime.datetime.now(utc) )
for k in self.__ts:
v = self.__ts[ k ]
ticketdt = to_datetime( v.getfielddef( 'changetime', timenow ) )
if ticketdt > timemax:
timemax = ticketdt
if timemax == timenow:
break
return timemax
示例14: _format_reminder
def _format_reminder(self, req, ticket, id, time, author, origin, description, delete_button=True):
now = to_datetime(None)
time = to_datetime(time)
if now >= time:
when = tag(tag.strong("Right now"), " (pending)")
else:
when = tag("In ", tag.strong(pretty_timedelta(time)), " (", format_date(time), ")")
if description:
context = Context.from_request(req, ticket.resource)
desc = tag.div(format_to_oneliner(self.env, context, description), class_="description")
else:
desc = tag()
return tag(self._reminder_delete_form(req, id) if delete_button else None, when, " - added by ", tag.em(Chrome(self.env).authorinfo(req, author)), " ", tag.span(pretty_timedelta(origin), title=format_datetime(origin, req.session.get('datefmt', 'iso8601'), req.tz)), " ago.", desc)
示例15: get_timeline_events
def get_timeline_events(self, req, start, stop, filters):
self.log.debug("start: %s, stop: %s, filters: %s" % (start, stop,
filters))
if ('discussion' in filters) and 'DISCUSSION_VIEW' in req.perm:
# Create request context.
context = Context.from_request(req)
context.realm = 'discussion-core'
# Get database access.
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Get API component.
api = self.env[DiscussionApi]
# Add CSS styles and scripts.
add_stylesheet(context.req, 'discussion/css/discussion.css')
# Get forum events.
for forum in api.get_changed_forums(context, start, stop):
# Return event.
title = 'New forum %s created' % (forum['name'],)
description = tag(format_to_oneliner(self.env, context,
forum['subject']), ' - ', format_to_oneliner(self.env,
context, forum['description']))
ids = ('forum', forum['id'])
yield ('discussion unsolved', to_datetime(forum['time'], utc),
forum['author'], (title, description, ids))
# Get topic events.
for topic in api.get_changed_topics(context, start, stop):
title = 'New topic on %s created' % (topic['forum_name'],)
description = format_to_oneliner(self.env, context,
topic['subject'])
ids = ('topic', topic['id'])
yield ('discussion solved' if 'solved' in topic['status']
else 'discussion unsolved', to_datetime(topic['time'], utc),
topic['author'], (title, description, ids))
# Get message events.
for message in api.get_changed_messages(context, start, stop):
title = 'New reply on %s created' % (message['forum_name'],)
description = format_to_oneliner(self.env, context,
message['topic_subject'])
ids = (('topic',message['topic']),'message', message['id'])
yield ('discussion unsolved', to_datetime(message['time'], utc),
message['author'], (title, description, ids))