def cert_time_to_seconds(cert_time):
"""Takes a date-time string in standard ASN1_print form
("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
a Python time value in seconds past the epoch."""
import time
return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
python类mktime()的实例源码
def __init__(self, allow_negative_scores=False, **kwargs):
# negative scores introduced in CB 4.2
# negative scores indicate a measure of "goodness" versus "badness"
self.allow_negative_scores = allow_negative_scores
# these fields are required in every report
self.required = ["iocs", "timestamp", "link", "title", "id", "score"]
# these fields must be of type string
self.typestring = ["link", "title", "id", "description"]
# these fields must be of type int
self.typeint = ["timestamp", "score"]
# these fields are optional
self.optional = ["tags", "description"]
# valid IOC types are "md5", "ipv4", "dns", "query"
self.valid_ioc_types = ["md5", "ipv4", "dns", "query"]
# valid index_type options for "query" IOC
self.valid_query_ioc_types = ["events", "modules"]
if "timestamp" not in kwargs:
kwargs["timestamp"] = int(time.mktime(time.gmtime()))
self.data = kwargs
def date_to_timestamp(date):
"""
Args:
date: Date as string with these formats: "Y-m-d", "Y-m-d H-M-S".
Returns:
"""
# format input string if only date but no time is provided
if len(date) == 10:
date = "{} 00:00:00".format(date)
return time.mktime(time.strptime(date, '%Y-%m-%d %H:%M:%S')) #
def _get_timestamp(self, date):
return int(time.mktime(date.timetuple()))
def parse_retry_after(self, retry_after):
# Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
if re.match(r"^\s*[0-9]+\s*$", retry_after):
seconds = int(retry_after)
else:
retry_date_tuple = email.utils.parsedate(retry_after)
if retry_date_tuple is None:
raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)
retry_date = time.mktime(retry_date_tuple)
seconds = retry_date - time.time()
if seconds < 0:
seconds = 0
return seconds
def parse_header(help_file, header_line):
"""
Given the name of a help file and its first line, return back a HeaderData
that provides the information from the header.
The return value is None if the line is not a valid file header.
"""
if not _header_prefix_re.match(header_line):
return None
result = re.findall(_header_keypair_re, header_line)
title = "No Title provided"
date = 0.0
for match in result:
if match[0] == "title":
title = match[1]
elif match[0] == "date":
try:
date = time.mktime(time.strptime(match[1], "%Y-%m-%d"))
except:
_log("Ignoring invalid file date '%s'", match[1])
date = 0.0
else:
_log("Ignoring header key '%s' in '%s'", match[0], help_file)
return HeaderData(help_file, title, date)
def format_rep_date(date_source):
date_source = re.search(u'\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}', date_source).group(0)
try:
timestamp = time.mktime(time.strptime(date_source, '%Y-%m-%d %H:%M'))
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
except:
return ''
def transfer_date(date_source):
try:
timestamp = time.mktime(time.strptime(date_source, '%Y-%m-%d %H:%M:%S'))
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
except:
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def format_date(date_source):
try:
timestamp = time.mktime(time.strptime(date_source, '%Y-%m-%d %H:%M:%S'))
return time.strftime('%Y-%m-%d', time.localtime(timestamp))
except:
return datetime.datetime.now().strftime("%Y-%m-%d")
def format_date_short(date_source):
try:
timestamp = time.mktime(time.strptime(date_source, '%Y-%m-%d'))
return time.strftime('%Y-%m-%d', time.localtime(timestamp))
except:
return datetime.datetime.now().strftime("%Y-%m-%d")
def compare_date_short(date1, date2):
try:
timestamp1 = time.mktime(time.strptime(date1, '%Y-%m-%d %H:%M:%S'))
timestamp2 = time.mktime(time.strptime(date2, '%Y-%m-%d %H:%M:%S'))
if timestamp1 > timestamp2:
return date1
return date2
except:
if date1 == '':
return date2
return date1
def get_date_diff_seconds(date1, date2):
timestamp1 = time.mktime(time.strptime(date1, '%Y-%m-%d %H:%M:%S'))
timestamp2 = time.mktime(time.strptime(date2, '%Y-%m-%d %H:%M:%S'))
return int(timestamp2 - timestamp1)
def prepare_time_range(time_from, time_to, relative_time_range, date_from=None, date_to=None):
"""
Prepare time range based on given options. Options are validated in advance.
"""
if relative_time_range:
return {"time_range": relative_time_range}
elif time_from and time_to:
return {"from": int(time_from) * 1000, "to": int(time_to) * 1000}
elif date_from and date_to:
from_ts = int(time.mktime(time.strptime(date_from, "%Y-%m-%d %H:%M:%S"))) * 1000
to_ts = int(time.mktime(time.strptime(date_to, "%Y-%m-%d %H:%M:%S"))) * 1000
return {"from": from_ts, "to": to_ts}
def __updateHead(self):
headT = self.font.get("head")
if not headT:
return
general = self.config.get("General")
style = self.config.get("Style")
if general:
version = general.get("version")
createdTime = general.get("createdTime")
modifiedTime = general.get("modifiedTime")
if isinstance(version, float) or isinstance(version, int):
headT.fontRevision = float(abs(version))
if isinstance(createdTime, datetime):
headT.created = long(mktime(datetime.timetuple(createdTime)) - epoch_diff)
if isinstance(modifiedTime, datetime):
headT.modified = long(mktime(datetime.timetuple(modifiedTime)) - epoch_diff)
self.font.recalcTimestamp = False
if style:
styleLink = style.get("styleLink")
widthScale = style.get("widthScale")
if styleLink in range(0, 5):
# Clear related bits first
headT.macStyle &= ~0b11
if styleLink == Constants.STYLELINK_BOLD:
headT.macStyle |= 1
elif styleLink == Constants.STYLELINK_ITALIC:
headT.macStyle |= 1<<1
elif styleLink == Constants.STYLELINK_BOLDITALIC:
headT.macStyle |= 1
headT.macStyle |= 1<<1
else:
pass
if widthScale in range(1, 10):
headT.macStyle &= ~(0b11<<5)
if widthScale < 5:
headT.macStyle |= 1<<5
elif widthScale > 5:
headT.macStyle |= 1<<6
else:
pass
return
def _to_timestamp(self, date):
return int(time.mktime(date.timetuple()))
def post(self):
if pubsub_utils.SUBSCRIPTION_UNIQUE_TOKEN != self.request.get('token'):
self.response.status = 404
return
# Store the message in the datastore.
message = json.loads(urllib.unquote(self.request.body).rstrip('='))
message_body = base64.b64decode(str(message['message']['data']))
message = message_body.split(',')
d = datetime.strptime(message[0][:-5],'%Y-%m-%dT%H:%M:%S')
timestamp = time.mktime(d.timetuple())
message = message[1:]
entities = zip(message[::2],map(int,message[1::2]))
data_raw = memcache.get(MC_OSCARS_TOP10)
if data_raw:
data = json.loads(memcache.get(MC_OSCARS_TOP10))
else:
data = None
if data is None or data['timestamp'] < timestamp:
memcache.set(MC_OSCARS_TOP10,json.dumps({
'timestamp': timestamp,
'entities': entities
}))
def local_time(time_utc):
u = int(time.mktime(time_utc.timetuple()))
time_local = datetime.datetime.fromtimestamp(u, pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
return str(time_local)
def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
return time.mktime(time.strptime(datestr, format))
def format_http_datetime(stamp):
""" Formats datetime to a string following rfc1123 pattern.
>>> now = datetime(2011, 9, 19, 10, 45, 30, 0, UTC)
>>> format_http_datetime(now)
'Mon, 19 Sep 2011 10:45:30 GMT'
if timezone is not set in datetime instance the ``stamp``
is assumed to be in UTC (``datetime.utcnow``).
>>> now = datetime(2011, 9, 19, 10, 45, 30, 0)
>>> format_http_datetime(now)
'Mon, 19 Sep 2011 10:45:30 GMT'
>>> now = datetime.utcnow()
>>> assert format_http_datetime(now)
if ``stamp`` is a string just return it
>>> format_http_datetime('x')
'x'
>>> format_http_datetime(100) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: ...
"""
if isinstance(stamp, datetime):
if stamp.tzinfo:
stamp = stamp.astimezone(UTC).timetuple()
else:
stamp = localtime(mktime(stamp.timetuple()))
elif isinstance(stamp, str):
return stamp
else:
raise TypeError('Expecting type ``datetime.datetime``.')
year, month, day, hh, mm, ss, wd, y, z = stamp
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
WEEKDAYS[wd], day, MONTHS[month], year, hh, mm, ss
)
def QA_util_date_stamp(date):
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date