Python源码示例:calendar.timegm()
示例1
def encode(self, payload, key, algorithm='HS256', headers=None,
json_encoder=None):
# Check that we get a mapping
if not isinstance(payload, Mapping):
raise TypeError('Expecting a mapping object, as JWT only supports '
'JSON objects as payloads.')
# Payload
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(payload.get(time_claim), datetime):
payload[time_claim] = timegm(payload[time_claim].utctimetuple())
json_payload = json.dumps(
payload,
separators=(',', ':'),
cls=json_encoder
).encode('utf-8')
return super(PyJWT, self).encode(
json_payload, key, algorithm, headers, json_encoder
)
示例2
def utc2timestamp(human_time):
regex1 = "\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}"
match = re.search(regex1, human_time)
if match:
formated = match.group()
else:
return None
strped_time = datetime.strptime(formated, c.time_fmt)
timestamp = timegm(strped_time.utctimetuple())
regex2 = "\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}(\.\d+)"
match = re.search(regex2, human_time)
if match:
timestamp += float(match.group(1))
else:
timestamp += float("0.000000")
return timestamp
示例3
def utc2timestamp(human_time):
regex1 = "\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}"
match = re.search(regex1, human_time)
if match:
formated = match.group()
else:
return None
strped_time = datetime.strptime(formated, c.time_fmt)
timestamp = timegm(strped_time.utctimetuple())
regex2 = "\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}(\.\d+)"
match = re.search(regex2, human_time)
if match:
timestamp += float(match.group(1))
else:
timestamp += float("0.000000")
return timestamp
示例4
def format_timestamp(ts):
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, numbers.Real):
pass
elif isinstance(ts, (tuple, time.struct_time)):
ts = calendar.timegm(ts)
elif isinstance(ts, datetime.datetime):
ts = calendar.timegm(ts.utctimetuple())
else:
raise TypeError("unknown timestamp type: %r" % ts)
return email.utils.formatdate(ts, usegmt=True)
示例5
def format_timestamp(ts):
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, numbers.Real):
pass
elif isinstance(ts, (tuple, time.struct_time)):
ts = calendar.timegm(ts)
elif isinstance(ts, datetime.datetime):
ts = calendar.timegm(ts.utctimetuple())
else:
raise TypeError("unknown timestamp type: %r" % ts)
return email.utils.formatdate(ts, usegmt=True)
示例6
def build_cookie_parameters(self, params):
domain_hash = self._generate_domain_hash()
params._utma = "%s.%s.%s.%s.%s.%s" % (
domain_hash,
self.visitor.unique_id,
calendar.timegm(self.visitor.first_visit_time.timetuple()),
calendar.timegm(self.visitor.previous_visit_time.timetuple()),
calendar.timegm(self.visitor.current_visit_time.timetuple()),
self.visitor.visit_count
)
params._utmb = '%s.%s.10.%s' % (
domain_hash,
self.session.track_count,
calendar.timegm(self.session.start_time.timetuple()),
)
params._utmc = domain_hash
cookies = []
cookies.append('__utma=%s;' % params._utma)
if params._utmz:
cookies.append('__utmz=%s;' % params._utmz)
if params._utmv:
cookies.append('__utmv=%s;' % params._utmv)
params.utmcc = '+'.join(cookies)
return params
示例7
def generate_jws_dict(self, **kwargs):
client_key = kwargs.get('client_key', oidc_rp_settings.CLIENT_ID)
now_dt = dt.datetime.utcnow()
expiration_dt = kwargs.get('expiration_dt', (now_dt + dt.timedelta(seconds=30)))
issue_dt = kwargs.get('issue_dt', now_dt)
nonce = kwargs.get('nonce', 'nonce')
ret = kwargs
ret.update({
'iss': kwargs.get('iss', oidc_rp_settings.PROVIDER_ENDPOINT),
'nonce': nonce,
'aud': kwargs.get('aud', client_key),
'azp': kwargs.get('azp', client_key),
'exp': timegm(expiration_dt.utctimetuple()),
'iat': timegm(issue_dt.utctimetuple()),
'nbf': timegm(kwargs.get('nbf', now_dt).utctimetuple()),
'sub': '1234',
})
return ret
示例8
def generate_jws_dict(self, **kwargs):
client_key = kwargs.get('client_key', oidc_rp_settings.CLIENT_ID)
now_dt = dt.datetime.utcnow()
expiration_dt = kwargs.get('expiration_dt', (now_dt + dt.timedelta(seconds=30)))
issue_dt = kwargs.get('issue_dt', now_dt)
nonce = kwargs.get('nonce', 'nonce')
return {
'iss': kwargs.get('iss', oidc_rp_settings.PROVIDER_ENDPOINT),
'nonce': nonce,
'aud': kwargs.get('aud', client_key),
'azp': kwargs.get('azp', client_key),
'exp': timegm(expiration_dt.utctimetuple()),
'iat': timegm(issue_dt.utctimetuple()),
'nbf': timegm(kwargs.get('nbf', now_dt).utctimetuple()),
'sub': '1234',
}
示例9
def generate_jws_dict(self, **kwargs):
client_key = kwargs.get('client_key', oidc_rp_settings.CLIENT_ID)
now_dt = dt.datetime.utcnow()
expiration_dt = kwargs.get('expiration_dt', (now_dt + dt.timedelta(seconds=30)))
issue_dt = kwargs.get('issue_dt', now_dt)
nonce = kwargs.get('nonce', 'nonce')
return {
'iss': kwargs.get('iss', oidc_rp_settings.PROVIDER_ENDPOINT),
'nonce': nonce,
'aud': kwargs.get('aud', client_key),
'azp': kwargs.get('azp', client_key),
'exp': timegm(expiration_dt.utctimetuple()),
'iat': timegm(issue_dt.utctimetuple()),
'nbf': timegm(kwargs.get('nbf', now_dt).utctimetuple()),
'sub': '1234',
}
示例10
def generate_jws_dict(self, **kwargs):
client_key = kwargs.get('client_key', oidc_rp_settings.CLIENT_ID)
now_dt = dt.datetime.utcnow()
expiration_dt = kwargs.get('expiration_dt', (now_dt + dt.timedelta(seconds=30)))
issue_dt = kwargs.get('issue_dt', now_dt)
nonce = kwargs.get('nonce', 'nonce')
return {
'iss': kwargs.get('iss', oidc_rp_settings.PROVIDER_ENDPOINT),
'nonce': nonce,
'aud': kwargs.get('aud', client_key),
'azp': kwargs.get('azp', client_key),
'exp': timegm(expiration_dt.utctimetuple()),
'iat': timegm(issue_dt.utctimetuple()),
'nbf': timegm(kwargs.get('nbf', now_dt).utctimetuple()),
'sub': '1234',
}
示例11
def __init__(
self,
log_group_name,
filter_pattern=DEFAULT_FILTER_PATTERN,
thread_count=0,
**kwargs
):
super().__init__('logs', **kwargs)
self.log_group_name = log_group_name
self.paginator_kwargs = {}
if filter_pattern is not None:
self.paginator_kwargs['filterPattern'] = filter_pattern
self.thread_count = thread_count
self.start_ms = timegm(self.start_time.utctimetuple()) * 1000
self.end_ms = timegm(self.end_time.utctimetuple()) * 1000
示例12
def test_class_ops_pytz(self):
def compare(x, y):
assert (int(Timestamp(x).value / 1e9) ==
int(Timestamp(y).value / 1e9))
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
compare(Timestamp.utcfromtimestamp(current_time),
datetime.utcfromtimestamp(current_time))
compare(Timestamp.fromtimestamp(current_time),
datetime.fromtimestamp(current_time))
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
compare(Timestamp.combine(date_component, time_component),
datetime.combine(date_component, time_component))
示例13
def test_class_ops_dateutil(self):
def compare(x, y):
assert (int(np.round(Timestamp(x).value / 1e9)) ==
int(np.round(Timestamp(y).value / 1e9)))
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now('UTC'), datetime.now(tzutc()))
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
compare(Timestamp.utcfromtimestamp(current_time),
datetime.utcfromtimestamp(current_time))
compare(Timestamp.fromtimestamp(current_time),
datetime.fromtimestamp(current_time))
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
compare(Timestamp.combine(date_component, time_component),
datetime.combine(date_component, time_component))
示例14
def IsPacificDST(now):
"""Helper for PacificTime to decide whether now is Pacific DST (PDT).
Args:
now: A pseudo-posix timestamp giving current time in PST.
Returns:
True if now falls within the range of DST, False otherwise.
"""
pst = time.gmtime(now)
year = pst[0]
assert year >= 2007
begin = calendar.timegm((year, 3, 8, 2, 0, 0, 0, 0, 0))
while time.gmtime(begin).tm_wday != SUNDAY:
begin += DAY
end = calendar.timegm((year, 11, 1, 2, 0, 0, 0, 0, 0))
while time.gmtime(end).tm_wday != SUNDAY:
end += DAY
return begin <= now < end
示例15
def __toLocal(cls, value):
#Convert current time to local.
if value.tzinfo is None:
#If meter is not use time zone.
return value
timestamp = calendar.timegm(value.utctimetuple())
local_dt = datetime.datetime.fromtimestamp(timestamp)
assert value.resolution >= datetime.timedelta(microseconds=1)
return local_dt.replace(microsecond=value.microsecond)
示例16
def to_unixtime(time_string, format_string):
with _STRPTIME_LOCK:
return int(calendar.timegm(time.strptime(str(time_string), format_string)))
示例17
def page(self):
changemsg = []
if cherrypy.session.id != cherrypy.session.originalid:
if cherrypy.session.originalid is None:
changemsg.append(
'Created new session because no session id was given.')
if cherrypy.session.missing:
changemsg.append(
'Created new session due to missing '
'(expired or malicious) session.')
if cherrypy.session.regenerated:
changemsg.append('Application generated a new session.')
try:
expires = cherrypy.response.cookie['session_id']['expires']
except KeyError:
expires = ''
return page % {
'sessionid': cherrypy.session.id,
'changemsg': '<br>'.join(changemsg),
'respcookie': cherrypy.response.cookie.output(),
'reqcookie': cherrypy.request.cookie.output(),
'sessiondata': list(cherrypy.session.items()),
'servertime': (
datetime.utcnow().strftime('%Y/%m/%d %H:%M') + ' UTC'
),
'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()),
'cpversion': cherrypy.__version__,
'pyversion': sys.version,
'expires': expires,
}
示例18
def step(self, amt=1):
z = calendar.timegm(time.gmtime(time.time()))
for i in range(32):
color = self.palette((z & (1 << i)) > 0)
if self._reverse:
i = 31 - i
start = (self._bitSpace + self._bitWidth) * i
self.layout.fill(color, start, start + self._bitWidth)
示例19
def _epoch(dt_tuple):
return calendar.timegm(dt_tuple.timetuple())
示例20
def _strtime_to_httpdate(dt):
return email_utils.formatdate(calendar.timegm(
iso8601.parse_date(dt).timetuple()), usegmt=True)
示例21
def _dt_to_decimal(utc):
"""Datetime to Decimal.
Some databases don't store microseconds in datetime
so we always store as Decimal unixtime.
"""
if utc is None:
return None
decimal.getcontext().prec = 30
return (decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) +
(decimal.Decimal(str(utc.microsecond)) /
decimal.Decimal("1000000.0")))
示例22
def time_diff(self, time1,time2):
'''
*
* Getting the offest by comparing both times from the unix epoch time and getting the difference.
*
'''
timeA = datetime.datetime.strptime(time1, '%I:%M:%S %p')
timeB = datetime.datetime.strptime(time2, '%I:%M:%S %p')
timeAEpoch = calendar.timegm(timeA.timetuple())
timeBEpoch = calendar.timegm(timeB.timetuple())
tdelta = abs(timeAEpoch) - abs(timeBEpoch)
return int(tdelta/60)
示例23
def cmd_encode(self, event, *args):
"""Encode a time. Multiple different formats are supported, e.g. YYYY-MM-DD HH:MM:SS 'time encode <date>'"""
# use the body directly so spaces are handled correctly.
date_str = event["content"]["body"][len("!time encode "):]
if date_str.lower().strip() == "now":
now = time.time()
return "Parsed as %s\n%s" % (datetime.datetime.utcfromtimestamp(now), now)
try:
d = parser.parse(date_str)
ts = calendar.timegm(d.timetuple())
return "Parsed as %s\n%s" % (d.strftime("%Y-%m-%d %H:%M:%S"), ts)
except ValueError:
return "Failed to parse '%s'" % date_str
示例24
def epoch(dt):
"""
Returns the epoch timestamp of a timezone-aware datetime object.
"""
return calendar.timegm(dt.astimezone(pytz.utc).timetuple())
示例25
def _validate_claims(self, payload, options, audience=None, issuer=None,
leeway=0, **kwargs):
if 'verify_expiration' in kwargs:
options['verify_exp'] = kwargs.get('verify_expiration', True)
warnings.warn('The verify_expiration parameter is deprecated. '
'Please use verify_exp in options instead.',
DeprecationWarning)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
if not isinstance(audience, (string_types, type(None))):
raise TypeError('audience must be a string or None')
self._validate_required_claims(payload, options)
now = timegm(datetime.utcnow().utctimetuple())
if 'iat' in payload and options.get('verify_iat'):
self._validate_iat(payload, now, leeway)
if 'nbf' in payload and options.get('verify_nbf'):
self._validate_nbf(payload, now, leeway)
if 'exp' in payload and options.get('verify_exp'):
self._validate_exp(payload, now, leeway)
if options.get('verify_iss'):
self._validate_iss(payload, issuer)
if options.get('verify_aud'):
self._validate_aud(payload, audience)
示例26
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,
)
示例27
def mktime_tz(data):
"""Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp."""
if data[9] is None:
# No zone info, so localtime is better assumption than GMT
return time.mktime(data[:8] + (-1,))
else:
t = calendar.timegm(data)
return t - data[9]
示例28
def _timegm(tt):
year, month, mday, hour, min, sec = tt[:6]
if ((year >= EPOCH_YEAR) and (1 <= month <= 12) and (1 <= mday <= 31) and
(0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)):
return timegm(tt)
else:
return None
示例29
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,
)
示例30
def time_str2str(date_string, from_format, to_format):
"""Convert a date string with given format to another format. Return
the original date string if it's type is not string or failed to parse or
convert it with format."""
if not isinstance(date_string, six.string_types):
_logger.warning(
'"date_string" must be a string type, found %s,'
' return the original date_string directly.',
type(date_string)
)
return date_string
try:
dt = datetime.strptime(date_string, from_format)
# Need to pre process '%s' in to_format here because '%s' is not
# available on all platforms. Even on supported platforms, the
# result may be different because it depends on implementation on each
# platform. Replace it with UTC timestamp here directly.
if to_format:
timestamp = calendar.timegm(dt.timetuple())
to_format = _fix_timestamp_format(to_format, str(timestamp))
to_format = _fix_microsecond_format(to_format, str(dt.microsecond))
return dt.strftime(to_format)
except Exception:
_logger.warning(
'Unable to convert date_string "%s" from format "%s" to "%s",'
' return the original date_string, cause=%s',
date_string,
from_format,
to_format,
traceback.format_exc()
)
return date_string