def _get_x509_days_left(x509):
date_fmt = '%Y%m%d%H%M%SZ'
current_datetime = datetime.datetime.utcnow()
not_after = time.strptime(x509.get_notAfter(), date_fmt)
not_before = time.strptime(x509.get_notBefore(), date_fmt)
ret = {'not_after': (datetime.datetime(*not_after[:6]) - current_datetime).days,
'not_before': (datetime.datetime(*not_before[:6]) - current_datetime).days}
return ret
python类strptime()的实例源码
def scroll(query, begin, until, prefix=None):
diff = timedelta(minutes=4)
while begin < until:
to = min(begin + diff, until)
res = DB.query(query % (pad(begin), pad(to)))
for batch in res:
for row in batch:
# truncate longer ids to match with shorter host names
if "container_id" in row:
row["container_id"] = row["container_id"][0:11]
time_col = row["time"][0:min(26, len(row["time"]) - 1)]
if len(time_col) == 19:
t = time.strptime(time_col, "%Y-%m-%dT%H:%M:%S")
else:
t = time.strptime(time_col, "%Y-%m-%dT%H:%M:%S.%f")
if prefix is not None:
for key in row.iterkeys():
if (key not in SKIP_PREFIX) and ((prefix + "|") not in key):
row[APP_METRIC_DELIMITER.join((prefix, key))] = row.pop(key)
yield (time.mktime(t), row)
begin = to
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def uptime(args):
with os.popen("docker inspect -f '{{json .State}}' " + args.container + " 2>&1") as pipe:
status = pipe.read().strip()
if "No such image or container" in status:
print "0"
else:
statusjs = json.loads(status)
if statusjs["Running"]:
uptime = statusjs["StartedAt"]
start = time.strptime(uptime[:19], "%Y-%m-%dT%H:%M:%S")
print int(time.time() - time.mktime(start))
else:
print "0"
# get the approximate disk usage
# alt docker inspect -s -f {{.SizeRootFs}} 49219085bdaa
# alt docker exec " + args.container + " du -s -b / 2> /dev/null
def test_startofyear(self):
sdds_soy = Time.startOfYear()
# calculate start of year
soy = datetime.datetime(*(time.strptime(self.cur_year_str+"-01-01 00:00:00",
"%Y-%m-%d %H:%M:%S")[0:6]))
soy_time=calendar.timegm(soy.timetuple())
self.assertEqual( sdds_soy, soy_time )
sdds_time = Time()
sdds_time.setFromTime(soy_time)
# calculate start of year
self.assertEqual( sdds_time.gmtime(), time.gmtime(soy_time) )
def timetuple(self):
return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
def _datetime_type(data):
t = time.strptime(data, "%Y%m%dT%H:%M:%S")
return datetime.datetime(*tuple(t)[:6])
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
def iso_2_utc(iso_ts):
if not iso_ts or iso_ts is None: return 0
delim = -1
if not iso_ts.endswith('Z'):
delim = iso_ts.rfind('+')
if delim == -1: delim = iso_ts.rfind('-')
if delim > -1:
ts = iso_ts[:delim]
sign = iso_ts[delim]
tz = iso_ts[delim + 1:]
else:
ts = iso_ts
tz = None
if ts.find('.') > -1:
ts = ts[:ts.find('.')]
try: d = datetime.datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S')
except TypeError: d = datetime.datetime(*(time.strptime(ts, '%Y-%m-%dT%H:%M:%S')[0:6]))
dif = datetime.timedelta()
if tz:
hours, minutes = tz.split(':')
hours = int(hours)
minutes = int(minutes)
if sign == '-':
hours = -hours
minutes = -minutes
dif = datetime.timedelta(minutes=minutes, hours=hours)
utc_dt = d - dif
epoch = datetime.datetime.utcfromtimestamp(0)
delta = utc_dt - epoch
try: seconds = delta.total_seconds() # works only on 2.7
except: seconds = delta.seconds + delta.days * 24 * 3600 # close enough
return seconds
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def QA_util_date_stamp(date):
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date
def QA_util_time_stamp(time_):
'''
???????%Y-%m-%d %H:%M:%S ??????
'''
if len(str(time_)) == 10:
# yyyy-mm-dd??
return time.mktime(time.strptime(time_, '%Y-%m-%d'))
elif len(str(time_)) == 16:
# yyyy-mm-dd hh:mm??
return time.mktime(time.strptime(time_, '%Y-%m-%d %H:%M'))
else:
timestr = str(time_)[0:19]
return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S'))
def QA_util_date_valid(date):
try:
time.strptime(date, "%Y-%m-%d")
return True
except:
return False
def _from_timestring(self, s):
try:
parts = s.split('.')
base_time = time.strptime(parts[0], "%H:%M:%S")
self.nanosecond_time = (base_time.tm_hour * Time.HOUR +
base_time.tm_min * Time.MINUTE +
base_time.tm_sec * Time.SECOND)
if len(parts) > 1:
# right pad to 9 digits
nano_time_str = parts[1] + "0" * (9 - len(parts[1]))
self.nanosecond_time += int(nano_time_str)
except ValueError:
raise ValueError("can't interpret %r as a time" % (s,))
def _from_datestring(self, s):
if s[0] == '+':
s = s[1:]
dt = datetime.datetime.strptime(s, self.date_format)
self._from_timetuple(dt.timetuple())
def interpret_datestring(val):
if val[-5] in ('+', '-'):
offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1')
val = val[:-5]
else:
offset = -time.timezone
for tformat in cql_timestamp_formats:
try:
tval = time.strptime(val, tformat)
except ValueError:
continue
# scale seconds to millis for the raw value
return (calendar.timegm(tval) + offset) * 1e3
else:
raise ValueError("can't interpret %r as a date" % (val,))
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
expires = time.time() + morsel['max-age']
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = time.mktime(
time.strptime(morsel['expires'], time_template)) - time.timezone
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)