def strftime(config, context, arg, now=time.gmtime()):
"""
strftime returns the current time (in UTC) converted to the format
specified by the first argument. The format is specified using
Python's time.strftime format (
https://docs.python.org/2/library/time.html#time.strftime).
Example:
{"CFPP::Strftime": "%Y%m%d_%H%M%S"} ==> 20060102_220405
Note: use special care when using this function with CloudFormation's
"update" functionality. The output of this function will change each
time cfpp is run.
"""
_raise_unless_string(context, arg)
return time.strftime(arg, now)
python类html()的实例源码
def DatetimeToUTCMicros(date):
"""Converts a datetime object to microseconds since the epoch in UTC.
Args:
date: A datetime to convert.
Returns:
The number of microseconds since the epoch, in UTC, represented by the input
datetime.
"""
# Using this guide: http://wiki.python.org/moin/WorkingWithTime
# And this conversion guide: http://docs.python.org/library/time.html
# Turn the date parameter into a tuple (struct_time) that can then be
# manipulated into a long value of seconds. During the conversion from
# struct_time to long, the source date in UTC, and so it follows that the
# correct transformation is calendar.timegm()
micros = calendar.timegm(date.utctimetuple()) * _MICROSECONDS_PER_SECOND
return micros + date.microsecond
def DatetimeToUTCMicros(date):
"""Converts a datetime object to microseconds since the epoch in UTC.
Args:
date: A datetime to convert.
Returns:
The number of microseconds since the epoch, in UTC, represented by the input
datetime.
"""
# Using this guide: http://wiki.python.org/moin/WorkingWithTime
# And this conversion guide: http://docs.python.org/library/time.html
# Turn the date parameter into a tuple (struct_time) that can then be
# manipulated into a long value of seconds. During the conversion from
# struct_time to long, the source date in UTC, and so it follows that the
# correct transformation is calendar.timegm()
micros = calendar.timegm(date.utctimetuple()) * _MICROSECONDS_PER_SECOND
return micros + date.microsecond
def posts_add(self, url, description, extended="", tags="", dt="",
replace="no", shared="yes", **kwds):
"""Add a post to del.icio.us. Returns a `result` message or raises an
``DeliciousError``. See ``self.request()``.
&url (required)
the url of the item.
&description (required)
the description of the item.
&extended (optional)
notes for the item.
&tags (optional)
tags for the item (space delimited).
&dt (optional)
datestamp of the item (format "CCYY-MM-DDThh:mm:ssZ").
Requires a LITERAL "T" and "Z" like in ISO8601 at http://www.cl.cam.ac.uk/~mgk25/iso-time.html for example: "1984-09-01T14:21:31Z"
&replace=no (optional) - don't replace post if given url has already been posted.
&shared=no (optional) - make the item private
"""
return self.request("posts/add", url=url, description=description,
extended=extended, tags=tags, dt=dt,
replace=replace, shared=shared, **kwds)
def formatOutputVars(self):
"""create output variable object for insertion into template."""
self.outputVars={"title":self.agencyName,"headerTitle":self.agencyName,"generationDate":email.utils.formatdate(localtime=True)}
routeSelect=""
tableTemplate="\t<section id='{0}'>\n\t\t<h1>{1}</h1>\n{2}\t</section>\n"
activeTemplate="\t\t<table><caption>{0}</caption><thead></thead><tbody></tbody></table>\n"
tables=""
for routename in self.selectedRoutes if len(self.selectedRoutes)>0 else self.routesByName.keys():
route=self.routesByName[routename]
routeSelect+="\t<input type='radio' name='line' value='{1}' id='radio-{1}'/><label for='radio-{1}'>{0}</label>\n".format(route.shortname,route.id)
routetables=""
for line in sorted(route.stops.keys()):
routetables+=activeTemplate.format(line)
tables+=tableTemplate.format(route.id,route.longname,routetables)
self.outputVars["ttimesettings"]=removeSpaces(json.dumps({"selectedRoutes":self.selectedRoutes,"excludeStops":self.excludeStops,"_12hourClock":self._12hourClock}))
self.outputVars["html"]=routeSelect+tables
self.outputVars["javascript"]="const dates={0};\nconst routes={1};\nconst _12hourClock={2};\n".format(removeSpaces(self.dates.__str__()),removeSpaces(self.routes.__str__().replace("'\\x00'","null")),str(self._12hourClock).lower())
def readHtmlTemplate(self,templateFilename="t-time.html"):
"""read entire HTML template and optionally insert CSS
arguments:
templateFilename -- optional, if template is different than t-time.html
"""
template=""
try:
with open(templateFilename,"r",encoding="utf-8") as templatefile:
for line in templatefile:
template+=line
except (FileNotFoundError,BaseException) as ex:
handleException(ex,
"File "+ex.filename+" does not exist. This is the HTML template to export the data.",
"There was a problem opening "+ex.filename+". This is the HTML template to export the data.")
if self.css is not None:
template=template.replace('<link rel="stylesheet" href="t-time.css" />',self.css,1)
self.template=Template(template)
def timezone(temp_tz):
"""Sets the timezone, yields, then resets the timezone.
Args:
temp_tz: See https://docs.python.org/2/library/time.html#time.tzset
"""
original_tz = get_timezone_environ()
set_timezone_environ(temp_tz)
try:
yield
finally:
set_timezone_environ(original_tz)
def strftime(string_format, second=None):
''' return a date string using string. See https://docs.python.org/2/library/time.html#time.strftime for format '''
if second is not None:
try:
second = int(second)
except:
raise errors.AnsibleFilterError('Invalid value for epoch value (%s)' % second)
return time.strftime(string_format, time.localtime(second))
def es_get_timestamp_filer(since=None):
# @see https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-range-query.html
return {
"range": {
"@timestamp": {
"gt": since,
}
}
} if since is not None else {}
def format_timestamp(ts):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
"""
tz_info = tz.tzutc()
return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z")
def get_log_aggregate(query, group_by, stats_field):
# @see https://www.elastic.co/guide/en/elasticsearch/reference/2.0/search-aggregations.html
# @see https://www.elastic.co/guide/en/elasticsearch/reference/2.0/search-aggregations-metrics-stats-aggregation.html
# @see https://www.elastic.co/guide/en/elasticsearch/reference/2.0/search-aggregations-bucket-terms-aggregation.html
aggs = {
"aggregations": {
"group_by_agg": {
"terms": {
"field": group_by
},
},
"aggregations": {
"stats" : { "field" : stats_field }
}
}
}
res = get_log_messages(query, extra=aggs, limit=0, batch=0, return_raw=True)
res = list(res)[0]
aggs = res['aggregations']
# print(aggs)
# build stats
buckets = {}
for agg in aggs['group_by_agg']['buckets']:
buckets[agg['key']] = agg['doc_count']
stats = aggs['aggregations']
return buckets, stats
def __init__(self):
"""extends html.parser.HTMLParser.__init__"""
html.parser.HTMLParser.__init__(self)
self.tag=None
self.foundTag=False
self.settings=None
self.agencyName=None
def handle_starttag(self,tag,attrs):
"""overides html.parser.HTMLParser.handle_starttag"""
self.tag=tag
if "script"==tag and len(attrs)==1 and "type"==attrs[0][0] and "application/x-t-time-settings"==attrs[0][1]:
self.foundTag=True
elif "title"==tag:
self.foundTag=True
def handle_data(self,data):
"""overides html.parser.HTMLParser.handle_data"""
if self.foundTag:
if "script"==self.tag:
self.settings=data
elif "title"==self.tag:
self.agencyName=data
def handle_endtag(self,tag):
"""overides html.parser.HTMLParser.handle_endtag"""
self.foundTag=False
def __init__(self,outputName=None,agencyName=None,inputZip=None,_12hourClock=True):
"""initialize some variables. can specify a zip file that contains the feed, otherwise will read files from cwd. can set a few things here."""
self.outputName=outputName
self.agencyName=agencyName # <title> in html output
self.inputZip=inputZip
self._12hourClock=_12hourClock # TODO: Automatically determine this based on current locale (python makes this unclear)
self.selectedRoutes=() # tuple of route IDs
self.excludeStops={} # dictionary of route IDs to lists of stop IDs