Python calendar.timegm() Examples

The following are 30 code examples for showing how to use calendar.timegm(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module calendar , or try the search function .

Example 1
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: MIT License 7 votes vote down vote up
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) 
Example 2
Project: gist-alfred   Author: danielecook   File: api_jwt.py    License: MIT License 6 votes vote down vote up
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
        ) 
Example 3
Project: misp42splunk   Author: remg427   File: ta_helper.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 4
Project: misp42splunk   Author: remg427   File: ta_helper.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 5
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: MIT License 6 votes vote down vote up
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) 
Example 6
Project: plugin.video.kmediatorrent   Author: jmarth   File: requests.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 7
Project: django-oidc-rp   Author: impak-finance   File: test_backends.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 6 votes vote down vote up
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',
        } 
Example 9
Project: django-oidc-rp   Author: impak-finance   File: test_authentication.py    License: MIT License 6 votes vote down vote up
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',
        } 
Example 10
Project: django-oidc-rp   Author: impak-finance   File: test_utils.py    License: MIT License 6 votes vote down vote up
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',
        } 
Example 11
Project: flowlogs-reader   Author: obsrvbl   File: flowlogs_reader.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 12
Project: recruit   Author: Frank-qlu   File: test_timestamp.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_timestamp.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 14
Project: browserscope   Author: elsigh   File: appcfg.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 15
Project: Gurux.DLMS.Python   Author: Gurux   File: GXDateTime.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 16
Project: jumpserver-python-sdk   Author: jumpserver   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def to_unixtime(time_string, format_string):
    with _STRPTIME_LOCK:
        return int(calendar.timegm(time.strptime(str(time_string), format_string))) 
Example 17
Project: cherrypy   Author: cherrypy   File: sessiondemo.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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,
        } 
Example 18
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: BinaryEpochClock.py    License: MIT License 5 votes vote down vote up
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) 
Example 19
Project: rate.sx   Author: chubin   File: interval.py    License: MIT License 5 votes vote down vote up
def _epoch(dt_tuple):
    return calendar.timegm(dt_tuple.timetuple()) 
Example 20
Project: gnocchi   Author: gnocchixyz   File: test_rest.py    License: Apache License 2.0 5 votes vote down vote up
def _strtime_to_httpdate(dt):
        return email_utils.formatdate(calendar.timegm(
            iso8601.parse_date(dt).timetuple()), usegmt=True) 
Example 21
Project: gnocchi   Author: gnocchixyz   File: sqlalchemy_types.py    License: Apache License 2.0 5 votes vote down vote up
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"))) 
Example 22
Project: pseudo-channel   Author: justinemter   File: PseudoChannel.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 23
Project: Matrix-NEB   Author: matrix-org   File: time_utils.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 24
Project: worker   Author: moira-alert   File: util.py    License: GNU General Public License v3.0 5 votes vote down vote up
def epoch(dt):
    """
    Returns the epoch timestamp of a timezone-aware datetime object.
    """
    return calendar.timegm(dt.astimezone(pytz.utc).timetuple()) 
Example 25
Project: gist-alfred   Author: danielecook   File: api_jwt.py    License: MIT License 5 votes vote down vote up
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) 
Example 26
Project: gist-alfred   Author: danielecook   File: cookies.py    License: MIT License 5 votes vote down vote up
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,
    ) 
Example 27
Project: verge3d-blender-addon   Author: Soft8Soft   File: _parseaddr.py    License: GNU General Public License v3.0 5 votes vote down vote up
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] 
Example 28
Project: verge3d-blender-addon   Author: Soft8Soft   File: cookiejar.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 29
Project: misp42splunk   Author: remg427   File: cookies.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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,
    ) 
Example 30
Project: misp42splunk   Author: remg427   File: ext.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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