Python calendar.timegm() Examples

The following are 30 code examples of calendar.timegm(). 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 also want to check out all available functions/classes of the module calendar , or try the search function .
Example #1
Source File: httputil.py    From tornado-zh with 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
Source File: utils.py    From jumpserver-python-sdk with GNU General Public License v2.0 6 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 #3
Source File: ta_helper.py    From misp42splunk with 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
Source File: ta_helper.py    From misp42splunk with 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
Source File: test_timestamp.py    From recruit with 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 #6
Source File: test_timestamp.py    From recruit with 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 #7
Source File: flowlogs_reader.py    From flowlogs-reader with 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 #8
Source File: api_jwt.py    From gist-alfred with 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 #9
Source File: httputil.py    From tornado-zh with 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 #10
Source File: requests.py    From plugin.video.kmediatorrent with 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 #11
Source File: appcfg.py    From browserscope with 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 #12
Source File: test_utils.py    From django-oidc-rp with 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 #13
Source File: test_authentication.py    From django-oidc-rp with 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 #14
Source File: test_middleware.py    From django-oidc-rp with 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 #15
Source File: test_backends.py    From django-oidc-rp with 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 #16
Source File: cookies.py    From plugin.video.emby with GNU 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 #17
Source File: base.py    From vj4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _datetime_stamp(dt):
  if not dt.tzinfo:
    dt = dt.replace(tzinfo=pytz.utc)
  return calendar.timegm(dt.utctimetuple())


# Decorators 
Example #18
Source File: GXDateTime.py    From Gurux.DLMS.Python with 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 #19
Source File: kraken.py    From crypto-arbitrage with MIT License 5 votes vote down vote up
def get_ticker_history(self, ticker, timeframe='1'):
        # 1 hour ago
        since = calendar.timegm((datetime.utcnow() - timedelta(hours = 1)).timetuple())
        return self._send_request('public/OHLC?pair={0}&interval={1}&since={2}'.format(ticker, timeframe, since), 'GET') 
Example #20
Source File: dtutil.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def parse_rfc3339(s: str) -> datetime.datetime:
    # pylint: disable=protected-access
    struct = feedparser._parse_date(s)
    return ts2dt(int(timegm(struct))) 
Example #21
Source File: cleanup-packer-aws-resources.py    From farley-aws-missing-tools with MIT License 5 votes vote down vote up
def dt2ts(dt):
    return calendar.timegm(dt.utctimetuple())

# Helper to convert seconds to a sexy format "x hours, x minutes, x seconds" etc 
Example #22
Source File: dev_appserver.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def CacheRewriter(response):
  """Update the cache header."""


  if response.status_code == httplib.NOT_MODIFIED:
    return

  if not 'Cache-Control' in response.headers:
    response.headers['Cache-Control'] = 'no-cache'
    if not 'Expires' in response.headers:
      response.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'


  if 'Set-Cookie' in response.headers:



    current_date = time.time()
    expires = response.headers.get('Expires')
    reset_expires = True
    if expires:
      expires_time = email.Utils.parsedate(expires)
      if expires_time:
        reset_expires = calendar.timegm(expires_time) >= current_date
    if reset_expires:
      response.headers['Expires'] = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                  time.gmtime(current_date))



    cache_directives = []
    for header in GetAllHeaders(response.headers, 'Cache-Control'):
      cache_directives.extend(v.strip() for v in header.split(','))
    cache_directives = [d for d in cache_directives if d != 'public']
    if not NON_PUBLIC_CACHE_CONTROLS.intersection(cache_directives):
      cache_directives.append('private')
    response.headers['Cache-Control'] = ', '.join(cache_directives) 
Example #23
Source File: json.py    From vj4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, o):
    if type(o) is objectid.ObjectId:
      return str(o)
    if type(o) is datetime.datetime:
      return calendar.timegm(o.utctimetuple()) * 1000
    return super(Encoder, self).default(o) 
Example #24
Source File: test_barbican_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def test_get_key(self):
        original_secret_metadata = mock.Mock()
        original_secret_metadata.algorithm = mock.sentinel.alg
        original_secret_metadata.bit_length = mock.sentinel.bit
        original_secret_metadata.secret_type = 'symmetric'

        key_id = "43ed09c3-e551-4c24-b612-e619abe9b534"
        key_ref = ("http://localhost:9311/v1/secrets/" + key_id)
        original_secret_metadata.secret_ref = key_ref

        created = timeutils.parse_isotime('2015-10-20 18:51:17+00:00')
        original_secret_metadata.created = created
        created_formatted = timeutils.parse_isotime(str(created))
        created_posix = calendar.timegm(created_formatted.timetuple())

        key_name = 'my key'
        original_secret_metadata.name = key_name

        original_secret_data = b'test key'
        original_secret_metadata.payload = original_secret_data

        self.mock_barbican.secrets.get.return_value = original_secret_metadata
        key = self.key_mgr.get(self.ctxt, self.key_id)

        self.get.assert_called_once_with(self.secret_ref)
        self.assertEqual(key_id, key.id)
        self.assertEqual(key_name, key.name)
        self.assertEqual(original_secret_data, key.get_encoded())
        self.assertEqual(created_posix, key.created) 
Example #25
Source File: test_ujson.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_encode_datetime_conversion(self):
        datetime_input = datetime.datetime.fromtimestamp(time.time())
        output = ujson.encode(datetime_input, date_unit="s")
        expected = calendar.timegm(datetime_input.utctimetuple())

        assert int(expected) == json.loads(output)
        assert int(expected) == ujson.decode(output) 
Example #26
Source File: test_imports.py    From python-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_csvbititerator_customtimefunc(self):
        class UtcTzinfo(datetime.tzinfo):
            ZERO = datetime.timedelta(0)
            def utcoffset(self, dt):
                return UtcTzinfo.ZERO
            def dst(self, dt):
                return UtcTzinfo.ZERO
            def tzname(self, dt):
                return "UTC"

        def timefunc_utcstr(timeval):
            dt = datetime.datetime.strptime(timeval, '%Y-%m-%dT%H:%M:%S')
            dt = dt.replace(tzinfo=UtcTzinfo())
            return calendar.timegm(dt.timetuple())

        reader = csv_column_reader(StringIO(u"""
            1,10,1991-09-02T06:33:20
            5,20,1991-09-02T06:35:00
            3,41,1991-09-02T06:36:25
            10,10485760,1991-09-02T06:36:25
        """), timefunc=timefunc_utcstr)

        rows = list(reader)
        self.assertEqual(len(rows), 4)
        self.assertEqual(rows[0], Column(row_id=1, column_id=10, timestamp=683793200))
        self.assertEqual(rows[1], Column(row_id=5, column_id=20, timestamp=683793300))
        self.assertEqual(rows[2], Column(row_id=3, column_id=41, timestamp=683793385))
        self.assertEqual(rows[3], Column(row_id=10, column_id=10485760, timestamp=683793385)) 
Example #27
Source File: heuristics.py    From jbox with MIT License 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #28
Source File: ical.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def nsdate_from_python_date(date):
	# TODO: Find a way to get a timestamp from python date without the calendar module
	date_as_tuple = date.timetuple()
	timestamp = pysyscal.timegm(date_as_tuple)
	
	return NSDate.alloc().initWithTimeIntervalSince1970_(timestamp) 
Example #29
Source File: utils.py    From django-oidc-rp with MIT License 5 votes vote down vote up
def _validate_claims(id_token, nonce=None, validate_nonce=True):
    """ Validates the claims embedded in the JSON Web Token. """
    iss_parsed_url = urlparse(id_token['iss'])
    provider_parsed_url = urlparse(oidc_rp_settings.PROVIDER_ENDPOINT)
    if iss_parsed_url.netloc != provider_parsed_url.netloc:
        raise SuspiciousOperation('Invalid issuer')

    if isinstance(id_token['aud'], str):
        id_token['aud'] = [id_token['aud']]

    if oidc_rp_settings.CLIENT_ID not in id_token['aud']:
        raise SuspiciousOperation('Invalid audience')

    if len(id_token['aud']) > 1 and 'azp' not in id_token:
        raise SuspiciousOperation('Incorrect id_token: azp')

    if 'azp' in id_token and id_token['azp'] != oidc_rp_settings.CLIENT_ID:
        raise SuspiciousOperation('Incorrect id_token: azp')

    utc_timestamp = timegm(dt.datetime.utcnow().utctimetuple())
    if utc_timestamp > id_token['exp']:
        raise SuspiciousOperation('Signature has expired')

    if 'nbf' in id_token and utc_timestamp < id_token['nbf']:
        raise SuspiciousOperation('Incorrect id_token: nbf')

    # Verifies that the token was issued in the allowed timeframe.
    if utc_timestamp > id_token['iat'] + oidc_rp_settings.ID_TOKEN_MAX_AGE:
        raise SuspiciousOperation('Incorrect id_token: iat')

    # Validate the nonce to ensure the request was not modified if applicable.
    id_token_nonce = id_token.get('nonce', None)
    if validate_nonce and oidc_rp_settings.USE_NONCE and id_token_nonce != nonce:
        raise SuspiciousOperation('Incorrect id_token: nonce') 
Example #30
Source File: flowlogs_reader.py    From flowlogs-reader with Apache License 2.0 5 votes vote down vote up
def to_message(self):
        D_transform = {
            'start': lambda dt: str(timegm(dt.utctimetuple())),
            'end': lambda dt: str(timegm(dt.utctimetuple())),
        }

        ret = []
        for attr in self.__slots__:
            transform = D_transform.get(attr, lambda x: str(x) if x else '-')
            ret.append(transform(getattr(self, attr)))

        return ' '.join(ret)