Python time.mktime() Examples

The following are code examples for showing how to use time.mktime(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 7 votes vote down vote up
def generateAPI(route):
    if private=='000':
        print('Private Key Missing. Open <GenerateAPI.py> file and Enter your Private Key')
        exit()
    
    d = datetime.datetime.now()
    unixtime = int(time.mktime(d.timetuple()))
    
    #Expiration Time kept to 1 hr
    expiration = 3600
    future = unixtime + expiration
    
    method = 'GET'
    stringToSign = public + ":" + method + ":" + route + ":" + str(future)
    
    sig = calculateSignature(stringToSign.encode(),private.encode())
    
    url = 'http://sites.ieee.org/sb-ritb/gravityformsapi/'+route+'/?api_key='+public+'&signature='+sig+'&expires='+str(future)
    return url 
Example 2
Project: flasky   Author: RoseOu   File: cookies.py    MIT License 7 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']:
        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,
    ) 
Example 3
Project: f5go   Author: f5devcentral   File: go.py    MIT License 6 votes vote down vote up
def __getattr__(self, attrname):
        if attrname == "totalClicks":
            return self.archivedClicks + sum(self.clickData.values())
        elif attrname == "recentClicks":
            return sum(self.clickData.values())
        elif attrname == "lastClickTime":
            if not self.clickData:
                return 0
            maxk = max(self.clickData.keys())
            return time.mktime(datetime.date.fromordinal(maxk).timetuple())
        elif attrname == "lastClickDay":
            if not self.clickData:
                return 0
            return max(self.clickData.keys())
        else:
            raise AttributeError(attrname) 
Example 4
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 6 votes vote down vote up
def generatePostAPI(route='forms'):
    if private=='000':
        print('Private Key Missing. Open <GenerateAPI.py> file and Enter your Private Key')
        sys.exit()
    
    d = datetime.datetime.now()
    unixtime = int(time.mktime(d.timetuple()))
    
    #Expiration Time kept to 1 hr
    expiration = 3600
    future = unixtime + expiration
    
    method = 'POST'
    stringToSign = public + ":" + method + ":" + route + ":" + str(future)
    
    sig = calculateSignature(stringToSign.encode(),private.encode())
    
    url = 'http://ieeeritb.in/gravityformsapi/'+route+'/?api_key='+public+'&signature='+sig+'&expires='+str(future)
    return url 
Example 5
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 6 votes vote down vote up
def generateAPI(route='forms'):
    if private=='000':
        print('Private Key Missing. Open <GenerateAPI.py> file and Enter your Private Key')
        exit()
    
    d = datetime.datetime.now()
    unixtime = int(time.mktime(d.timetuple()))
    
    #Expiration Time kept to 1 hr
    expiration = 3600
    future = unixtime + expiration
    
    method = 'GET'
    stringToSign = public + ":" + method + ":" + route + ":" + str(future)
    
    sig = calculateSignature(stringToSign.encode(),private.encode())
    
    url = 'http://sites.ieee.org/sb-ritb/gravityformsapi/'+route+'/?api_key='+public+'&signature='+sig+'&expires='+str(future)
    return url 
Example 6
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 6 votes vote down vote up
def generatePostAPI(route='forms'):
    if private=='000':
        print('Private Key Missing. Open <GenerateAPI.py> file and Enter your Private Key')
        sys.exit()
    
    d = datetime.datetime.now()
    unixtime = int(time.mktime(d.timetuple()))
    
    #Expiration Time kept to 1 hr
    expiration = 3600
    future = unixtime + expiration
    
    method = 'POST'
    stringToSign = public + ":" + method + ":" + route + ":" + str(future)
    
    sig = calculateSignature(stringToSign.encode(),private.encode())
    
    url = 'http://ieeeritb.in/gravityformsapi/'+route+'/?api_key='+public+'&signature='+sig+'&expires='+str(future)
    return url 
Example 7
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 6 votes vote down vote up
def generateAPI(route='forms'):
    if private=='000':
        print('Private Key Missing. Open <GenerateAPI.py> file and Enter your Private Key')
        exit()
    
    d = datetime.datetime.now()
    unixtime = int(time.mktime(d.timetuple()))
    
    #Expiration Time kept to 1 hr
    expiration = 3600
    future = unixtime + expiration
    
    method = 'GET'
    stringToSign = public + ":" + method + ":" + route + ":" + str(future)
    
    sig = calculateSignature(stringToSign.encode(),private.encode())
    
    url = 'http://sites.ieee.org/sb-ritb/gravityformsapi/'+route+'/?api_key='+public+'&signature='+sig+'&expires='+str(future)
    return url 
Example 8
Project: oeffis-paper   Author: djaffry   File: api_oebb.py    MIT License 6 votes vote down vote up
def _extract_line_and_calc_countdown(connection):
        line = {
            # 'name': data['sections'][0]['category']['displayName'].rjust(3),  # alternative name
            'name': connection['sections'][0]['category']['shortName'].rjust(3),
            'direction': connection['sections'][0]['to']['name'],
            'barrierFree': 'disabled' in connection['sections'][0]['category']['journeyPreviewIconId'],
            'trafficJam': 'departureDelay' in connection['sections'][0]['from']
        }
        if line['trafficJam']:  # if there is a delay, use departureDelay value instead
            departure_time = time.strptime(connection['sections'][0]['from']['departureDelay'][:-3], "%Y-%m-%dT%H:%M:%S.")
        else:
            departure_time = time.strptime(connection['sections'][0]['from']['departure'][:-3], "%Y-%m-%dT%H:%M:%S.")
        countdown = round((time.mktime(departure_time) - time.mktime(time.localtime())) / 60)
        line['departures'] = [max(0, countdown)]
        station = {'lines': [line], 'name': connection['sections'][0]['from']['name']}
        return station 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: letsencrypt.py    MIT License 6 votes vote down vote up
def get_cert_days(module, cert_file):
    '''
    Return the days the certificate in cert_file remains valid and -1
    if the file was not found. If cert_file contains more than one
    certificate, only the first one will be considered.
    '''
    if not os.path.exists(cert_file):
        return -1

    openssl_bin = module.get_bin_path('openssl', True)
    openssl_cert_cmd = [openssl_bin, "x509", "-in", cert_file, "-noout", "-text"]
    dummy, out, dummy = module.run_command(openssl_cert_cmd, check_rc=True, encoding=None)
    try:
        not_after_str = re.search(r"\s+Not After\s*:\s+(.*)", out.decode('utf8')).group(1)
        not_after = datetime.fromtimestamp(time.mktime(time.strptime(not_after_str, '%b %d %H:%M:%S %Y %Z')))
    except AttributeError:
        module.fail_json(msg="No 'Not after' date found in {0}".format(cert_file))
    except ValueError:
        module.fail_json(msg="Failed to parse 'Not after' date of {0}".format(cert_file))
    now = datetime.utcnow()
    return (not_after - now).days


# function source: network/basics/uri.py 
Example 10
Project: flasky   Author: RoseOu   File: cookies.py    MIT License 6 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"]:
        expires = time.time() + morsel["max-age"]
    elif morsel['expires']:
        expires = morsel['expires']
        if type(expires) == type(""):
            time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
            expires = time.mktime(time.strptime(expires, time_template))
    c = create_cookie(
        name=morsel.key,
        value=morsel.value,
        version=morsel['version'] or 0,
        port=None,
        domain=morsel['domain'],
        path=morsel['path'],
        secure=bool(morsel['secure']),
        expires=expires,
        discard=False,
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,)
    return c 
Example 11
Project: tmanager   Author: ssh3ll   File: dates.py    MIT License 6 votes vote down vote up
def date_to_epoch(date_time: str) -> float:
    """
    Returns the 'epoch-time' equivalent of the date taken as a parameter.

    :param str date_time: date to convert in epoch. It MUST BE in dd-mm-yyyy format
    :return float: seconds to epoch
    """
    try:
        date_time = str(datetime.datetime.strptime(date_time, '%d-%m-%Y')).split(" ")[0]
    except ValueError:
        raise click.BadParameter(msg.Echoes.error("Bad data format! It must be dd-mm-yyyy"), param="--last-update-date",
                                 param_hint="Date format MUST BE dd-mm-yyyy")

    date_time = "{}-0-0-0-0-0-0".format(date_time)
    # noinspection PyTypeChecker
    date_time = time.mktime(tuple([int(e) for e in date_time.split("-")]))
    return date_time 
Example 12
Project: AshsSDK   Author: thehappydinoa   File: cookies.py    MIT License 6 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']:
        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,
    ) 
Example 13
Project: InsightAgent   Author: insightfinder   File: reportMetrics.py    Apache License 2.0 6 votes vote down vote up
def update_data_start_time():
    if "FileReplay" in parameters['mode'] and reporting_config_vars['prev_endtime'] != "0" and len(
            reporting_config_vars['prev_endtime']) >= 8:
        start_time = reporting_config_vars['prev_endtime']
        # pad a second after prev_endtime
        start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")));
        end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval']
    elif reporting_config_vars['prev_endtime'] != "0":
        start_time = reporting_config_vars['prev_endtime']
        # pad a second after prev_endtime
        start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")));
        end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval']
    else:  # prev_endtime == 0
        end_time_epoch = int(time.time()) * 1000
        start_time_epoch = end_time_epoch - 1000 * 60 * reporting_config_vars['reporting_interval']
    return start_time_epoch


# update prev_endtime in config file 
Example 14
Project: deb-python-cassandra-driver   Author: openstack   File: statements.py    Apache License 2.0 6 votes vote down vote up
def timestamp_normalized(self):
        """
        we're expecting self.timestamp to be either a long, int, a datetime, or a timedelta
        :return:
        """
        if not self.timestamp:
            return None

        if isinstance(self.timestamp, six.integer_types):
            return self.timestamp

        if isinstance(self.timestamp, timedelta):
            tmp = datetime.now() + self.timestamp
        else:
            tmp = self.timestamp

        return int(time.mktime(tmp.timetuple()) * 1e+6 + tmp.microsecond) 
Example 15
Project: wpbiff   Author: gszathmari   File: brutesession.py    MIT License 6 votes vote down vote up
def get_server_time(self):
        """
        Gets remote server time using HTTP
        """
        headers = {
            'User-Agent': self.user_agent
        }
        # Sometimes HEAD requests fail so we try multiple times
        for attempt in range(10):
            try:
                r = requests.head(self.url, headers=headers)
            except requests.exceptions.ConnectionError:
                time.sleep(3)
            else:
                break
        if r.status_code == 200:
            t = parsedate(r.headers['Date'])
            return datetime.fromtimestamp(time.mktime(t))
        else:
            raise Exception('Remote server did not respond. Is it down?') 
Example 16
Project: jawfish   Author: war-and-code   File: cookies.py    MIT License 6 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']:
        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,
    ) 
Example 17
Project: pyblish-win   Author: pyblish   File: _parseaddr.py    GNU Lesser 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 18
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsedate_acceptable_to_time_functions(self):
        eq = self.assertEqual
        timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup)), 2003)
        timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup[:9]))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup[:9])), 2003) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsedate_acceptable_to_time_functions(self):
        eq = self.assertEqual
        timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup)), 2003)
        timetup = utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup[:9]))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup[:9])), 2003) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        # Try an arbitrary fixed value.
        year, month, day = 1999, 9, 19
        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
        d = self.theclass.fromtimestamp(ts)
        self.assertEqual(d.year, year)
        self.assertEqual(d.month, month)
        self.assertEqual(d.day, day) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_conversions(self):
        self.assertTrue(time.ctime(self.t)
                     == time.asctime(time.localtime(self.t)))
        self.assertTrue(long(time.mktime(time.localtime(self.t)))
                     == long(self.t)) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_gmtime_without_arg(self):
        gt0 = time.gmtime()
        gt1 = time.gmtime(None)
        t0 = time.mktime(gt0)
        t1 = time.mktime(gt1)
        self.assertTrue(0 <= (t1-t0) < 0.2) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_localtime_without_arg(self):
        lt0 = time.localtime()
        lt1 = time.localtime(None)
        t0 = time.mktime(lt0)
        t1 = time.mktime(lt1)
        self.assertTrue(0 <= (t1-t0) < 0.2) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mktime(self):
        # Issue #1726687
        for t in (-2, -1, 0, 1):
            try:
                tt = time.localtime(t)
            except (OverflowError, ValueError):
                pass
            else:
                self.assertEqual(time.mktime(tt), t) 
Example 25
Project: pyblish-win   Author: pyblish   File: rfc822.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getdate(self, name):
        """Retrieve a date field from a header.

        Retrieves a date field from the named header, returning a tuple
        compatible with time.mktime().
        """
        try:
            data = self[name]
        except KeyError:
            return None
        return parsedate(data) 
Example 26
Project: pyblish-win   Author: pyblish   File: rfc822.py    GNU Lesser 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 UTC timestamp."""
    if data[9] is None:
        # No zone info, so localtime is better assumption than GMT
        return time.mktime(data[:8] + (-1,))
    else:
        t = time.mktime(data[:8] + (0,))
        return t - data[9] - time.timezone 
Example 27
Project: oeffis-paper   Author: djaffry   File: display_driver.py    MIT License 5 votes vote down vote up
def _adjust_to_render_offset(transport_data):
        """
        Unfortunately the waveshare display takes about 60 seconds to display the information.
        Therefore the displayed time can be corrected by adding `renderOffset` to the server time minutes and
        subtracting `renderOffset` from the countdown time

        Input:
        Uses data from `config.json` with the following keys:
        display (json):                       display json with the following keys:
            renderOffset (number, optional):            offset in minutes used to add to displayed server time and subtract countdown

        :param transport_data
        :return: time adjusted transport_data
        """

        conf = get_config()
        if 'renderOffset' in conf['display']:
            corrected_seconds = time.mktime(transport_data['lastUpdate']) + conf['display']['renderOffset'] * 60
            transport_data['lastUpdate'] = time.localtime(corrected_seconds)

            offset_data = []
            for s in transport_data['stations']:
                for l in s['lines']:
                    # subtract `renderOffset` from countdown time
                    l['departures'] = [d - conf['display']['renderOffset']
                                       for d in l['departures'] if d - conf['display']['renderOffset'] >= 0]
                    if not l['departures']:
                        s['lines'].remove(l)  # removing lines with no departure time
                if s['lines']:
                    offset_data.append(s)  # removing stations with no lines
            return {'stations': offset_data, 'lastUpdate': transport_data['lastUpdate']}
        else:
            return transport_data 
Example 28
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 5 votes vote down vote up
def date_string_to_datetime(s):
    "Convert date string to a datetime object using parsedatetime.Calendar()."

    # It's a shame that such a great library like parsedatetime
    # didn't go the extra inch and provide a decent API to get a
    # datetime object out of it.
    return datetime.fromtimestamp(mktime(parsedatetime.Calendar().parse(s)[0]))

# * Setup Click 
Example 29
Project: slidoc   Author: mitotic   File: sliauth.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_utc_date(date_time_str, pre_midnight=False):
    """Convert local date string of the form yyyy-mm-ddThh:mm (or yyyy-mm-dd) to UTC (unless it already ends with 'Z')"""
    if date_time_str and not date_time_str.endswith('Z'):
        if re.match(r'^\d\d\d\d-\d\d-\d\d$', date_time_str):
            date_time_str += 'T23:59' if pre_midnight else 'T00:00'
        try:
            date_time_str = datetime.datetime.utcfromtimestamp(time.mktime(time.strptime(date_time_str, "%Y-%m-%dT%H:%M"))).strftime("%Y-%m-%dT%H:%M") + 'Z'
        except Exception, excp:
            raise Exception("Error in parsing date '%s'; expect local time to be formatted like 2016-05-04T11:59 (%s)" % (date_time_str, excp)) 
Example 30
Project: slidoc   Author: mitotic   File: sliauth.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_date(date_time_str, pre_midnight=False, strict=False):
    """Parse ISO format date, with or without Z suffix denoting UTC, to return datetime object (containing local time)
       On error, raise Exception if strict else return None
    """
    if not date_time_str:
        return None

    if isinstance(date_time_str, datetime.datetime):
        return date_time_str

    if not isinstance(date_time_str, (str, unicode)):
        raise Exception('Expecting date_time string but received '+str(type(date_time_str))+' instead')
    
    if re.match(r'^\d\d\d\d-\d\d-\d\d$', date_time_str):
        date_time_str += 'T23:59' if pre_midnight else 'T00:00'

    if date_time_str.endswith('Z'):
        # UTC time step (add local time offset)
        offset_sec = time.mktime(datetime.datetime.now().timetuple()) - time.mktime(datetime.datetime.utcnow().timetuple())
        date_time_str = date_time_str[:-1]
    else:
        offset_sec = 0

    if len(date_time_str) == 16:
        # yyyy-mm-ddThh:mm
        format = "%Y-%m-%dT%H:%M"
    elif len(date_time_str) == 19:
        # yyyy-mm-ddThh:mm:ss
        format = "%Y-%m-%dT%H:%M:%S"
    else:
        format = "%Y-%m-%dT%H:%M:%S.%f"

    try:
        return datetime.datetime.fromtimestamp(time.mktime(time.strptime(date_time_str, format)) + offset_sec)
    except Exception:
        if strict:
            raise Exception('Invalid date string "%s"; expecting YYYYMMDD[Thh:mm]' % date_time_str)
        return None 
Example 31
Project: slidoc   Author: mitotic   File: sliauth.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def epoch_ms(date_time=None):
    """Return epoch milliseconds (i.e., milliseconds since Jan. 1, 1970) for datetime object"""
    if not date_time:
        return epoch_ms(datetime.datetime.now())

    date_time = parse_date(date_time, strict=True)
    return time.mktime(date_time.timetuple())*1000.0 + date_time.microsecond/1000.0 
Example 32
Project: Flask-pyoidc   Author: zamzterz   File: test_flask_pyoidc.py    Apache License 2.0 5 votes vote down vote up
def test_session_expiration_set_to_configured_lifetime(self, time_mock, utc_time_sans_frac_mock):
        timestamp = time.mktime(datetime(2017, 1, 1).timetuple())
        time_mock.return_value = timestamp
        utc_time_sans_frac_mock.return_value = int(timestamp)

        exp_time = 10
        state = 'test_state'
        nonce = 'test_nonce'
        id_token = IdToken(iss=self.PROVIDER_BASEURL,
                           aud=self.CLIENT_ID,
                           sub='sub1',
                           exp=int(timestamp) + exp_time,
                           iat=int(timestamp),
                           nonce=nonce)
        token_response = {'access_token': 'test', 'token_type': 'Bearer', 'id_token': id_token.to_jwt()}
        token_endpoint = self.PROVIDER_BASEURL + '/token'
        responses.add(responses.POST, token_endpoint, json=token_response)

        session_lifetime = 1234
        self.app.config['PERMANENT_SESSION_LIFETIME'] = session_lifetime
        self.init_app(provider_metadata_extras={'token_endpoint': token_endpoint})

        with self.app.test_client() as client:
            with client.session_transaction() as session:
                UserSession(session, self.PROVIDER_NAME)
                session['destination'] = '/'
                session['state'] = state
                session['nonce'] = nonce
            resp = client.get('/redirect_uri?state={}&code=test'.format(state))

        cookies = SimpleCookie()
        cookies.load(resp.headers['Set-Cookie'])
        session_cookie_expiration = cookies[self.app.config['SESSION_COOKIE_NAME']]['expires']
        parsed_expiration = datetime.strptime(session_cookie_expiration, '%a, %d-%b-%Y %H:%M:%S GMT')
        cookie_lifetime = (parsed_expiration - datetime.utcnow()).total_seconds()
        assert cookie_lifetime == pytest.approx(session_lifetime, abs=1) 
Example 33
Project: zmirror   Author: aploium   File: cache_system.py    MIT License 5 votes vote down vote up
def _time_str_to_unix(timestring):
    """
    :type timestring: Union[str, int]
    :rtype: Union[int, None]
    """
    if isinstance(timestring, (int, float)):
        return timestring
    try:
        t = int(time.mktime(datetime.strptime(timestring, '%a, %d %b %Y %H:%M:%S %Z').timetuple()))
    except:
        t = None
    return t 
Example 34
Project: bitmm   Author: thmp   File: coinbase.py    MIT License 5 votes vote down vote up
def parseTime(self, trade):
        #print trade
        t = datetime.datetime.strptime(trade["created_at"], "%Y-%m-%dT%H:%M:%S.%fZ")
        return time.mktime(t.timetuple()) 
Example 35
Project: openplotter   Author: openplotter   File: SK-base_d.py    GNU General Public License v2.0 5 votes vote down vote up
def Action_Calc_cycle(self, tick2a):
		now = tick2a
		for index, item in enumerate(self.triggers):
			error = False
			operator_ = item[2]
			if item[1] == -1:
				try:
					data_value = datetime.datetime.strptime(item[3], '%Y-%m-%dT%H:%M:%S')
					data_value = time.mktime(data_value.timetuple())
					data_value = float(data_value)
				except Exception, e: 
					print str(e)
					error = True
				if not error:
					# less than or equal to
					if operator_ == 4:
						self.Action_set(item, now <= data_value)
					# greater than or equal to
					elif operator_ == 6:
						self.Action_set(item, now >= data_value)
			else:
				if item[6] == 'value':
					try:
						trigger_value = item[1][1][2]
						try:
							data_value = float(item[3])
						except:
							data_value = str(item[3])
					except Exception, e: 
						print str(e)
						error = True
				elif item[6] == 'source':
					try:
						trigger_value = item[1][1][0]
						try:
							data_value = float(item[3])
						except:
							data_value = str(item[3])
					except Exception, e: 
						print str(e)
						error = True 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: retry.py    MIT License 5 votes vote down vote up
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 
Example 38
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 39
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: apt.py    MIT License 5 votes vote down vote up
def get_updated_cache_time():
    """Return the mtime time stamp and the updated cache time.
    Always retrieve the mtime of the apt cache or set the `cache_mtime`
    variable to 0
    :returns: ``tuple``
    """
    cache_mtime = get_cache_mtime()
    mtimestamp = datetime.datetime.fromtimestamp(cache_mtime)
    updated_cache_time = int(time.mktime(mtimestamp.timetuple()))
    return mtimestamp, updated_cache_time


# https://github.com/ansible/ansible-modules-core/issues/2951 
Example 40
Project: esp-sdk-python   Author: EvidentSecurity   File: api_authentication.py    MIT License 5 votes vote down vote up
def _request_date(self):
        now = datetime.now()
        tt = mktime(now.timetuple())
        return format_date_time(tt) 
Example 41
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        date_time = zip_stat.date_time + (0, 0, -1)  # ymdhms+wday, yday, dst
        #1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 42
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        date_time = zip_stat.date_time + (0, 0, -1)  # ymdhms+wday, yday, dst
        #1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 43
Project: Splunk_CBER_App   Author: MHaggis   File: process_search.py    MIT License 5 votes vote down vote up
def generate(self):
        self.logger.info("query %s" % self.query)
        i = 0
        for bindata in self.cb.process_search_iter(self.query):
            i += 1
            if i > 1000:
                # TODO: let's stop at 1,000 results for now?
                self.finish()
                return

            temp = dict((field_name, bindata[field_name]) for field_name in self.field_names)
            temp['sourcetype'] = 'bit9:carbonblack:json'

            #
            # Sometimes we have seen 'start' be equal to -1
            #
            try:
                temp['_time'] = int(time.mktime(dateutil.parser.parse(bindata['start']).timetuple()))
            except Exception as e:
                self.logger.exception('parsing bindata["start"] %s' % bindata['start'])
                temp['_time'] = 0

            temp['link_process'] = self.cb_server + '/#/analyze/' + bindata['id'] + "/1"
            temp['source'] = 'cbapi'
            temp['_raw'] = json.dumps(temp)
            yield temp

            if i % 10 == 0:
                self.flush() 
Example 44
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
                     + dt.hour * 3600
                     + dt.minute * 60
                     + dt.second)
        return time.localtime(timestamp+time.timezone).tm_isdst 
Example 45
Project: PySent   Author: nicolasteodosio   File: task.py    GNU General Public License v2.0 5 votes vote down vote up
def add_date_fields(tweet):
    created_at_datetime = parser.parse(tweet['created_at'])
    tweet['created_at_datetime'] = created_at_datetime - timedelta(hours=3)
    tweet['created_at_timestamp'] = time.mktime(created_at_datetime.timetuple())

    return tweet 
Example 46
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 47
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 48
Project: bigquerylayers   Author: smandaric   File: retry.py    GNU General Public License v3.0 5 votes vote down vote up
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 
Example 49
Project: bigquerylayers   Author: smandaric   File: reference.py    GNU General Public License v3.0 5 votes vote down vote up
def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0 
Example 50
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 51
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 52
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example 53
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 5 votes vote down vote up
def _on_success(self, future, **kwargs):
        filename = future.meta.call_args.fileobj
        try:
            last_update_tuple = self._last_modified_time.timetuple()
            mod_timestamp = time.mktime(last_update_tuple)
            set_file_utime(filename, int(mod_timestamp))
        except Exception as e:
            warning_message = (
                'Successfully Downloaded %s but was unable to update the '
                'last modified time. %s' % (filename, e))
            self._result_queue.put(create_warning(filename, warning_message)) 
Example 54
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt, fold_naive=True):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        if not self._hasdst:
            return False

        # Check for ambiguous times:
        dstval = self._naive_is_dst(dt)
        fold = getattr(dt, 'fold', None)

        if self.is_ambiguous(dt):
            if fold is not None:
                return not self._fold(dt)
            else:
                return True

        return dstval 
Example 55
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    Apache License 2.0 5 votes vote down vote up
def updateDataStartTime():
    if reportingConfigVars['prev_endtime'] != "0":
        startTime = reportingConfigVars['prev_endtime']
        # pad a second after prev_endtime
        startTimeEpoch = 1000 + long(1000 * time.mktime(time.strptime(startTime, "%Y%m%d%H%M%S")));
        end_time_epoch = startTimeEpoch + 1000 * 60 * reportingConfigVars['reporting_interval']
    else:  # prev_endtime == 0
        end_time_epoch = int(time.time()) * 1000
        startTimeEpoch = end_time_epoch - 1000 * 60 * reportingConfigVars['reporting_interval']
    return startTimeEpoch 
Example 56
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    Apache License 2.0 5 votes vote down vote up
def set_epoch_time(reporting_interval_l, prev_endtime_l):
    if prev_endtime_l != "0":
        start_time = prev_endtime_l
        # pad a second after prev_end_time
        start_time_epoch_l = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")))
        # end_time_epoch = start_time_epoch_l + 1000 * 60 * reporting_interval_l
        start_time_epoch_l = start_time_epoch_l / 1000
    else:  # prev_endtime == 0
        end_time_epoch = int(time.time()) * 1000
        start_time_epoch_l = end_time_epoch - 1000 * 60 * reporting_interval_l
        start_time_epoch_l = start_time_epoch_l / 1000
    return reporting_interval_l, start_time_epoch_l, prev_endtime_l


# update prev_endtime in config file 
Example 57
Project: douyin   Author: luocaiwei   File: tools.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def date_to_time(date):
    timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    _str = int(f'{timeStamp}000')
    return _str 
Example 58
Project: mimic   Author: googlearchive   File: target_env.py    Apache License 2.0 5 votes vote down vote up
def _Stat(self, original, path):
    in_target, resolved_path = _ResolvePath(path)
    if in_target:
      if self._IsStaticFile(path):
        # _IsStaticFile doesn't take paths returned from _ResolvePath, so use
        # the original path (_IsStaticFile removes _TARGET_PREFIX separately
        # from _ResolvePath)
        # Note that this will get raised even for files or directories that
        # don't exist, but whose path still match a static_dir/static_files
        # handler. Raise ENOENT and not EACCESS because when deployed, you'll
        # get ENOENT and not EACCESS.
        raise OSError(errno.ENOENT, _ACCESSING_STATIC_FILE_ERROR_MSG % path)
      elif self._IsSkippedFile(path):
        # Similar to _IsStaticFile above, use the original path
        raise OSError(errno.ENOENT, _ACCESSING_SKIPPED_FILE_ERROR_MSG % path)
      elif self._tree.HasFile(resolved_path):
        last_modified = self._tree.GetFileLastModified(resolved_path)
        return _MakeStatResult(_FILE_STAT_MODE,
                               self._tree.GetFileSize(resolved_path),
                               time.mktime(last_modified.timetuple()))
      elif self._tree.HasDirectory(resolved_path):
        return _MakeStatResult(_DIR_STAT_MODE)
      else:
        raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), resolved_path)
    else:
      # if the path is not in the target file system, defer to the original
      # os.stat (usually for absolute paths like python library files, or
      # some invalid absolute path)
      return original(resolved_path)

  # patches for os.path 
Example 59
Project: Kitsu.Bundle   Author: AeonLucid   File: retry.py    MIT License 5 votes vote down vote up
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 
Example 60
Project: quart   Author: pgjones   File: __init__.py    MIT License 5 votes vote down vote up
def default(self, object_: Any) -> Any:
        if isinstance(object_, date):
            return formatdate(timeval=mktime((object_.timetuple())), localtime=False, usegmt=True)
        if isinstance(object_, UUID):
            return str(object_)
        if hasattr(object_, "__html__"):
            return str(object_.__html__())
        return super().default(object_) 
Example 61
Project: local-info   Author: ianmiell   File: wsgi.py    MIT License 5 votes vote down vote up
def get_trains(data):
	for station in ('NDL',):
		url = 'http://ojp.nationalrail.co.uk/service/ldbboard/dep/' + station
		req = urllib2.Request(url)
		response = urllib2.urlopen(req)
		the_page = response.read()
		soup = bs4.BeautifulSoup(the_page)
		div = soup.find_all('div','tbl-cont')
		for tr in div:
			for tr in tr.find_all('tr'):
				count = 1
				route = ''
				destination = ''
				status = 'OK'
				t = ''
				arriving = ''
				for td in tr.find_all('td'):
					if td.string:
						s = td.string.strip()
						if count == 1:
							h = int(s.split(':')[0])
							m = int(s.split(':')[1])
							t = int(time.mktime((global_year,global_mon,global_day,h,m,global_sec,global_wday,global_yday,global_isdst)))
						elif count == 2:
							route = s
							destination = s
						elif count == 3:
							status = s
					else:
						s = str(td)
					count += 1
				if t != '':
					data.append({'from':'NDL','type':'TRAIN','route':route,'destination':destination,'leaving':int(t),'arriving':'','status':status}) 
Example 62
Project: slack-admin   Author: littlepea   File: utils.py    MIT License 5 votes vote down vote up
def get_timestamp_from_date_string(date_string):
    """Returns timestamp from a human-readable date string

    :param date_string: Human-readable date string (ex: "1 month ago", "1 Jan, 2017")
    :return: datetime object
    """
    parsed_date = parse_date_string(date_string)
    if parsed_date:
        timestamp = int(time.mktime(parsed_date.timetuple()))
        return timestamp 
Example 63
Project: openhatch   Author: campbe13   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def heartbeat_timestamp(self):
        return mktime(self.last_heartbeat.timetuple()) 
Example 64
Project: openhatch   Author: campbe13   File: timer2.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def to_timestamp(d):
    if isinstance(d, datetime):
        return mktime(d.timetuple())
    return d 
Example 65
Project: openhatch   Author: campbe13   File: reference.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0 
Example 66
Project: Andromeda   Author: liucaide   File: cd_tools.py    MIT License 5 votes vote down vote up
def cd_time_to_timestamp(date, strftime="%Y-%m-%d %H:%M:%S"):
    """
    :param date: 时间来源
    :param strftime: 时间格式
    :return: 根据时间格式返回格式化输入时间date
    """
    return time.mktime(time.strptime(date,strftime)) 
Example 67
Project: sound-of-sunshine   Author: waldoj   File: sunshine.py    MIT License 5 votes vote down vote up
def daily_cumulative():
    """Calculate the cumulative power use and generation since midnight."""

    # Figure out the timestamp for midnight, when today started.
    today = datetime.date.today()
    d = datetime.datetime(today.year, today.month, today.day)
    midnight = int(decimal.Decimal(time.mktime(d.timetuple())).normalize())
    
    cursor.execute("SELECT time, used, generated \
                    FROM energy \
                    WHERE used IS NOT NULL AND time >= ?",
                    ((midnight,)))
    records = cursor.fetchall()

    prior = midnight
    used = []
    generated = []
    for record in records:
        duration = int(record['time'] - prior)
        used.append(round(float(record['used']) / 3600 * float(duration), 2))
        prior = record['time']

    cumulative = {}
    if len(used) > 0:
        cumulative['used'] = round(sum(used) / len(used) * 10000)
    else:
        cumulative['used'] = 0

    return cumulative 
Example 68
Project: SYNC_NEO   Author: OTCGO   File: v2node.py    MIT License 5 votes vote down vote up
def get_now_timepoint():
    return str(time.mktime(datetime.datetime.now().timetuple())).split('.')[0] 
Example 69
Project: SYNC_NEO   Author: OTCGO   File: bonus.py    MIT License 5 votes vote down vote up
def prepare_status(self, now):
        node_bonus = await self.db.get_status('node_bonus')
        if node_bonus == -1:
            await self.db.update_status('node_bonus', 0)
        node_bonus_timepoint = await self.db.get_status('node_bonus_timepoint')
        if node_bonus_timepoint == -1:
            bonus_time = now
            if C.get_bonus_start_time() != 'now':
                bonus_time = time.mktime(datetime.fromtimestamp(bonus_time).date().timetuple())+10

            await self.db.update_status('node_bonus_timepoint', bonus_time) 
Example 70
Project: pyblish-win   Author: pyblish   File: imaplib.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def Internaldate2tuple(resp):
    """Parse an IMAP4 INTERNALDATE string.

    Return corresponding local time.  The return value is a
    time.struct_time instance or None if the string has wrong format.
    """

    mo = InternalDate.match(resp)
    if not mo:
        return None

    mon = Mon2num[mo.group('mon')]
    zonen = mo.group('zonen')

    day = int(mo.group('day'))
    year = int(mo.group('year'))
    hour = int(mo.group('hour'))
    min = int(mo.group('min'))
    sec = int(mo.group('sec'))
    zoneh = int(mo.group('zoneh'))
    zonem = int(mo.group('zonem'))

    # INTERNALDATE timezone must be subtracted to get UT

    zone = (zoneh*60 + zonem)*60
    if zonen == '-':
        zone = -zone

    tt = (year, mon, day, hour, min, sec, -1, -1, -1)

    utc = time.mktime(tt)

    # Following is necessary because the time module has no 'mkgmtime'.
    # 'mktime' assumes arg in local timezone, so adds timezone/altzone.

    lt = time.localtime(utc)
    if time.daylight and lt[-1]:
        zone = zone + time.altzone
    else:
        zone = zone + time.timezone

    return time.localtime(utc - zone) 
Example 71
Project: django-feedaggregator   Author: fasouto   File: tasks.py    MIT License 4 votes vote down vote up
def update_feed(feed):
    """
    Update the feed content and fetch latest items.
    """
    logger.debug("Processing feed %s" % feed)
    parsed_feed = feedparser.parse(feed.feed_url)

    if parsed_feed.bozo:  # Handle error in feed
        logger.error("Error in feed %s: %s" % (feed.feed_url, parsed_feed.bozo_exception))
        return

    if feed.is_new:
        title = parsed_feed.feed.get('title', "-")
        if not title:  # Check for empty strings
            title = "<Untitled>"

        link = parsed_feed.feed.get('link')
        description = parsed_feed.feed.get('description', "")

        if 'updated_parsed' in parsed_feed.feed:
            feed.updated_on = datetime.fromtimestamp(mktime(parsed_feed.feed.updated_parsed))

        # Save the feed info in the db
        feed.title = title
        feed.site_url = link
        feed.description = description
        feed.save()

    # Save the feed items
    for entry in parsed_feed.entries:
        if all(k in entry for k in ("title", "link")):
            print(entry)
            entry_title = entry.get('title', "<Untitled>")
            if not entry_title:  # Check for empty strings
                entry_title = "<Untitled>"

            # Sometimes feed titles change, this is why we don't user get_or_create
            try:
                feed_item = Item.objects.get(feed=feed, link=entry.link)
                feed_item.title = entry_title[:255]
            except Item.DoesNotExist:
                feed_item = Item(feed=feed, link=entry.link, title=entry_title[:255])

            feed_item.description = entry.get('description', "")
            feed_item.guid = entry.get('id', "")

            if 'published_parsed' in entry:
                feed_item.published_on = datetime.fromtimestamp(mktime(entry.published_parsed))
            feed_item.save()

            # Add the tags
            for tag_dict in entry.get('tags', ''):
                term = tag_dict.get('term', '')
                if FEEDAGGREGATOR_TAGS_LOWERCASE:
                    term = term.lower()
                feed_item.tags.add(term) 
Example 72
Project: Flask-pyoidc   Author: zamzterz   File: test_flask_pyoidc.py    Apache License 2.0 4 votes vote down vote up
def test_handle_authentication_response(self, time_mock, utc_time_sans_frac_mock):
        # freeze time since ID Token validation includes expiration timestamps
        timestamp = time.mktime(datetime(2017, 1, 1).timetuple())
        time_mock.return_value = timestamp
        utc_time_sans_frac_mock.return_value = int(timestamp)

        # mock token response
        user_id = 'user1'
        exp_time = 10
        nonce = 'test_nonce'
        id_token_claims = {
            'iss': self.PROVIDER_BASEURL,
            'aud': [self.CLIENT_ID],
            'sub': user_id,
            'exp': int(timestamp) + exp_time,
            'iat': int(timestamp),
            'nonce': nonce
        }
        id_token_jwt, id_token_signing_key = signed_id_token(id_token_claims)
        access_token = 'test_access_token'
        token_response = {'access_token': access_token, 'token_type': 'Bearer', 'id_token': id_token_jwt}
        token_endpoint = self.PROVIDER_BASEURL + '/token'
        responses.add(responses.POST, token_endpoint, json=token_response)
        responses.add(responses.GET,
                      self.PROVIDER_BASEURL + '/jwks',
                      json={'keys': [id_token_signing_key.serialize()]})

        # mock userinfo response
        userinfo = {'sub': user_id, 'name': 'Test User'}
        userinfo_endpoint = self.PROVIDER_BASEURL + '/userinfo'
        responses.add(responses.GET, userinfo_endpoint, json=userinfo)

        authn = self.init_app(provider_metadata_extras={'token_endpoint': token_endpoint,
                                                        'userinfo_endpoint': userinfo_endpoint})
        state = 'test_state'
        with self.app.test_request_context('/redirect_uri?state={}&code=test'.format(state)):
            UserSession(flask.session, self.PROVIDER_NAME)
            flask.session['destination'] = '/'
            flask.session['state'] = state
            flask.session['nonce'] = nonce
            authn._handle_authentication_response()
            session = UserSession(flask.session)
            assert session.access_token == access_token
            assert session.id_token == id_token_claims
            assert session.id_token_jwt == id_token_jwt
            assert session.userinfo == userinfo 
Example 73
Project: Flask-pyoidc   Author: zamzterz   File: test_flask_pyoidc.py    Apache License 2.0 4 votes vote down vote up
def test_handle_implicit_authentication_response(self, time_mock, utc_time_sans_frac_mock):
        # freeze time since ID Token validation includes expiration timestamps
        timestamp = time.mktime(datetime(2017, 1, 1).timetuple())
        time_mock.return_value = timestamp
        utc_time_sans_frac_mock.return_value = int(timestamp)

        # mock auth response
        access_token = 'test_access_token'
        user_id = 'user1'
        exp_time = 10
        nonce = 'test_nonce'
        id_token_claims = {
            'iss': self.PROVIDER_BASEURL,
            'aud': [self.CLIENT_ID],
            'sub': user_id,
            'exp': int(timestamp) + exp_time,
            'iat': int(timestamp),
            'nonce': nonce,
            'at_hash': jws.left_hash(access_token)
        }
        id_token_jwt, id_token_signing_key = signed_id_token(id_token_claims)

        responses.add(responses.GET,
                      self.PROVIDER_BASEURL + '/jwks',
                      json={'keys': [id_token_signing_key.serialize()]})

        # mock userinfo response
        userinfo = {'sub': user_id, 'name': 'Test User'}
        userinfo_endpoint = self.PROVIDER_BASEURL + '/userinfo'
        responses.add(responses.GET, userinfo_endpoint, json=userinfo)

        authn = self.init_app(provider_metadata_extras={'userinfo_endpoint': userinfo_endpoint})
        state = 'test_state'
        auth_response = AuthorizationResponse(
            **{'state': state, 'access_token': access_token, 'token_type': 'Bearer', 'id_token': id_token_jwt})
        with self.app.test_request_context('/redirect_uri?{}'.format(auth_response.to_urlencoded())):
            UserSession(flask.session, self.PROVIDER_NAME)
            flask.session['destination'] = '/'
            flask.session['state'] = state
            flask.session['nonce'] = nonce
            authn._handle_authentication_response()
            session = UserSession(flask.session)
            assert session.access_token == access_token
            assert session.id_token == id_token_claims
            assert session.id_token_jwt == id_token_jwt
            assert session.userinfo == userinfo 
Example 74
Project: neu-eone.py   Author: yearsyan   File: nespider.py    MIT License 4 votes vote down vote up
def library_info(self):
        library_url = self.__library_url()
        response_data = requests.get(library_url, proxies=proxies['library'])
        borrow_url = \
        re.findall('外借[\s\S]*?href="javascript:replacePage\(\'(.*?)\'\)', str(response_data.content, 'utf8'))[0]
        history_url = \
        re.findall('借阅历史列表[\s\S]*?href="javascript:replacePage\(\'(.*?)\'\)', str(response_data.content, 'utf8'))[0]
        borrow_res = str(requests.get(borrow_url, proxies=proxies['library']).content, 'utf8')
        history_res = str(requests.get(history_url, proxies=proxies['library']).content, 'utf8')

        history = re.findall('<td class=td1 valign=top><a href=".*?" target=_blank>(.*?)</a></td>[\s\S]*?target=_blank>(.*?)</a></td>\
[\s\S]*?<td class=td1 valign=top>(.*?)</td>[\s\S]*?<td class=td1 valign=top>(.*?)</td>[\s\S]*?<td class=td1 valign=top>(.*?)</td>\
[\s\S]*?<td class=td1 valign=top>(.*?)</td>[\s\S]*?<td class=td1 valign=top>(.*?)</td>[\s\S]*?<td class=td1 valign=top><br></td>[\s\S]*?\
<td class=td1 valign=top>(.*?)</td>', history_res)

        writers = re.findall('<td class=td1 valign=top width="8%" >(.*?)<', borrow_res)
        books = re.findall('target=_blank>(.*?)</a></td', borrow_res)
        back_day = re.findall('<td class=td1 valign=top width="10%">(.*?)</td>', borrow_res)
        books_code = re.findall('<input type="checkbox" name="(.*?)"></td>', borrow_res)
        # extend_url 是用来续借的时候使用的,不必透露给用户,在library_continue_borrow中使用了这个链接
        extend_url = re.findall('var strData = "(.*?)"', borrow_res)[0]

        res = [
            {
                'writer': writers[i],
                'book': books[i],
                'back_day': back_day[2 * i],
                'book_code': books_code[i],
            }
            for i in range(0, len(writers))
        ]
        histories = [
            {
                'writer': history[i][0],
                'name': history[i][1],
                'publish_year': history[i][2],
                # 为了方便存储与传输,我将借书、还书时间由人类公元纪年法转化为unix时间戳
                'back_time': int(time.mktime(time.strptime(history[i][3] + ' ' + history[i][4], '%Y%m%d %H:%M'))),
                'real_back_time': int(time.mktime(time.strptime(history[i][5] + ' ' + history[i][6], '%Y%m%d %H:%M'))),
                'type': history[i][7]
            }
            for i in range(0, len(history))
        ]

        return {'extend_url': extend_url, 'book_data': res, 'history': histories}

    # 获取每一批次考试的具体信息 
Example 75
Project: Crop-Watch   Author: objectsyndicate   File: views.py    Apache License 2.0 4 votes vote down vote up
def flot_ajax(request, start, end, uuid):
    data = ""
    # check if the incoming values are integers,
    try:
        int(start) and int(end)
        # are they 13 digit integers, (are they timestamps)
        if len(start) == 13 and len(end) == 13:
            t1 = []
            t2 = []
            h = []
            uv = []
            l = []
            # does the user have an iotank?
            if not ioTank.objects.filter(owner=request.user):
                bots = None
            else:
                bots = ioTank.objects.get(owner=request.user, id=uuid)
                # Z for UTC %z for localtz
                start = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(start) / 1000.))
                end = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(end) / 1000.))
                readings = SensorReading.objects.filter(bot=bots, timestamp__range=(start, end)).order_by('timestamp')
                for i in readings:
                    if bots.u == 'F':
                        i.t1 = 9.0 / 5.0 * int(i.t1) + 32
                        i.t2 = 9.0 / 5.0 * int(i.t2) + 32
                    t1_list = []
                    t2_list = []
                    h_list = []
                    uv_list = []
                    l_list = []

                    unixtime = int(time.mktime(i.timestamp.timetuple()) * 1000)

                    t1_list.append(unixtime)
                    t1_list.append(float(i.t1))
                    t1.append(t1_list)

                    t2_list.append(unixtime)
                    t2_list.append(int(i.t2))
                    t2.append(t2_list)

                    h_list.append(unixtime)
                    h_list.append(int(i.h))
                    h.append(h_list)

                    uv_list.append(unixtime)
                    uv_list.append(float(i.uv))
                    uv.append(uv_list)

                    l_list.append(unixtime)
                    l_list.append(float(i.l))
                    l.append(l_list)

            data = '{"data":{"t1":' + str(t1) + ',"t2":' + str(t2) + ',"h":' + str(h) + ',"uv":' + str(
                uv) + ',"l":' + str(l) + '}}'
    except ValueError:
        return HttpResponse(start + end, content_type='application/json')
    return HttpResponse(data, content_type='application/json')


# List all devices 
Example 76
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    Apache License 2.0 4 votes vote down vote up
def getMetricsFromFile(profileFolder, filePath, rawDataMap):
        command = 'nfdump -M ' + profileFolder + '/bittorrent:top:upstream1:p2p:sip:rdp:mysql:ms-sql-s:http-alt:microsoft-ds:https:snmp:netbios-ns:loc-srv:ntp:http:dns:telnet:ssh:ftp:chargen:icmp -r ' + filePath + ' -o csv -a -A proto,srcip,srcport,dstip,dstport -O tstart > ' + "out.csv"
        output = subprocess.check_output(command, shell=True)
        logger.debug("Command ran: " + command)
        #parse the csv generated by nfdump
        with open("out.csv") as metricFile:
            metricCSVReader = csv.reader(metricFile)
            maxLen = 0
            for row in metricCSVReader:
                if metricCSVReader.line_num == 1:
                    # Get all the metric names from header
                    fieldnames = row
                    maxLen = len(fieldnames)
                    # get index of the timestamp column
                    for i in range(0, len(fieldnames)):
                        if fieldnames[i] == "ts":
                            timestampIndex = i
                elif metricCSVReader.line_num > 1:
                    if len(row) < maxLen:
                        continue
                    sourceAddress = row[3] + ":" + row[5]
                    destAddress = row[4] + ":" + row[6]
                    protocol = row[7]
                    hostName = sourceAddress + "_" + destAddress + "_" + protocol

                    timestamp = int(time.mktime(datetime.datetime.strptime(row[1], "%Y-%m-%d %H:%M:%S").timetuple())) * 1000
                    duration = row[2]
                    inPackets = row[11]
                    inBytes = row[12]
                    outPackets = row[13]
                    outBytes = row[14]
                    if timestamp in rawDataMap:
                        valueMap = rawDataMap[timestamp]
                    else:
                        valueMap = {}

                    valueMap['Duration[' + hostName + ']:9900'] = duration
                    valueMap['InPackets[' + hostName + ']:9901'] = inPackets
                    valueMap['InBytes[' + hostName + ']:9902'] = inBytes
                    valueMap['OutPackets[' + hostName + ']:9903'] = outPackets
                    valueMap['OutBytes[' + hostName + ']:9904'] = outBytes
                    rawDataMap[timestamp] = valueMap 
Example 77
Project: epschedule   Author: guberti   File: main.py    MIT License 4 votes vote down vote up
def get(self):
        # Get the cookie
        id = self.check_id()
        if id is None:
            self.send_login_response()
            return

        if id == DEMO_ID:  # If this is the demo account
            id = GAVIN_ID
        # schedule = self.get_schedule(self.request.get('id'))
        schedule = self.get_schedule(id)
        lunch_objs = update_lunch.getLunchForDate(datetime.date.today())

        if schedule is not None:

            show_privacy_dialog = False

            if self.request.cookies.get("SEENPRIVDIALOG") != "1":
                if schedule["grade"]:  # If the user is a student
                    user_obj_query = self.query_by_email(id_to_email(id))
                    obj = user_obj_query.get()
                    if obj:
                        show_privacy_dialog = not obj.seen_update_dialog
                if not show_privacy_dialog:
                    expiration_date = datetime.datetime.now()
                    expiration_date += datetime.timedelta(
                        3650
                    )  # Set expiration date 10 years in the future
                    self.response.set_cookie(
                        "SEENPRIVDIALOG", "1", expires=expiration_date
                    )

            # Handler for how to serialize date objs into json
            template_values = {
                "schedule": json.dumps(schedule),
                "days": json.dumps(DAYS),
                "components": self.get_components_filename(),
                "lunches": json.dumps(lunch_objs),
                "self_photo": json.dumps(
                    self.gen_photo_url(schedule["username"], "school_photos")
                ),
                "show_privacy_dialog": json.dumps(show_privacy_dialog),
                # Multiply by 1000 to give Unix time in milliseconds
                "fall_end_unix": str(int(time.mktime(FALL_TRI_END.timetuple())) * 1000),
                "wint_end_unix": str(int(time.mktime(WINT_TRI_END.timetuple())) * 1000),
            }

            template = JINJA_ENVIRONMENT.get_template("index.html")
            self.response.write(template.render(template_values))
        else:
            self.response.write("No schedule for id " + id) 
Example 78
Project: ngo-addons-backport   Author: camptocamp   File: stock_graph.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def draw(self):
        colors = choice_colors(len(self._datas.keys()))
        user_color = {}
        for user in self._datas.keys():
            user_color[user] = colors.pop()

        val_min = int(time.mktime(time.strptime(self.val_min,'%Y-%m-%d')))
        val_max = int(time.mktime(time.strptime(self.val_max,'%Y-%m-%d')))

        plots = []
        for product_id in self._datas:
            f = fill_style.Plain()
            f.bgcolor = user_color[user]
            datas = self._datas[product_id].items()
            datas = map(lambda x: (int(time.mktime(time.strptime(x[0],'%Y-%m-%d'))),x[1]), datas)
            datas.sort()
            datas2 = []
            val = 0
            for d in datas:
                val+=d[1]

                if len(datas2):
                    d2 = d[0]-60*61*24
                    if datas2[-1][0]<d2-1000:
                        datas2.append((d2,datas2[-1][1]))
                datas2.append((d[0],val))
            if len(datas2) and datas2[-1][0]<val_max-100:
                datas2.append((val_max, datas2[-1][1]))
            if len(datas2)==1:
                datas2.append( (datas2[0][0]+100, datas2[0][1]) )
            st = line_style.T()
            st.color = user_color[product_id]
            st.width = 1
            st.cap_style=1
            st.join_style=1
            plot = line_plot.T(label=self._names[product_id], data=datas2, line_style=st)
            plots.append(plot)

        interval = max((val_max-val_min)/15, 86400)
        x_axis = axis.X(format=lambda x:'/a60{}'+time.strftime('%Y-%m-%d',time.gmtime(x)), tic_interval=interval, label=None)
        # For add the report header on the top of the report.
        tb = text_box.T(loc=(300, 500), text="/hL/15/bStock Level Forecast", line_style=None)
        tb.draw()
        ar = area.T(size = (620,435), x_range=(val_min,val_max+1), y_axis = axis.Y(format="%d", label="Virtual Stock (Unit)"), x_axis=x_axis)
        for plot in plots:
            ar.add_plot(plot)
        ar.draw(self._canvas) 
Example 79
Project: deb-python-cassandra-driver   Author: openstack   File: query.py    Apache License 2.0 4 votes vote down vote up
def execute(self):
        if self._executed and self.warn_multiple_exec:
            msg = "Batch executed multiple times."
            if self._context_entered:
                msg += " If using the batch as a context manager, there is no need to call execute directly."
            warn(msg)
        self._executed = True

        if len(self.queries) == 0:
            # Empty batch is a no-op
            # except for callbacks
            self._execute_callbacks()
            return

        opener = 'BEGIN ' + (self.batch_type + ' ' if self.batch_type else '') + ' BATCH'
        if self.timestamp:

            if isinstance(self.timestamp, six.integer_types):
                ts = self.timestamp
            elif isinstance(self.timestamp, (datetime, timedelta)):
                ts = self.timestamp
                if isinstance(self.timestamp, timedelta):
                    ts += datetime.now()  # Apply timedelta
                ts = int(time.mktime(ts.timetuple()) * 1e+6 + ts.microsecond)
            else:
                raise ValueError("Batch expects a long, a timedelta, or a datetime")

            opener += ' USING TIMESTAMP {0}'.format(ts)

        query_list = [opener]
        parameters = {}
        ctx_counter = 0
        for query in self.queries:
            query.update_context_id(ctx_counter)
            ctx = query.get_context()
            ctx_counter += len(ctx)
            query_list.append('  ' + str(query))
            parameters.update(ctx)

        query_list.append('APPLY BATCH;')

        tmp = conn.execute('\n'.join(query_list), parameters, self._consistency, self._timeout, connection=self._connection)
        check_applied(tmp)

        self.queries = []
        self._execute_callbacks() 
Example 80
Project: ffplayout-engine   Author: ffplayout   File: ffplayout.py    GNU General Public License v3.0 4 votes vote down vote up
def get_playlist(self):
        if stdin_args.playlist:
            self.json_file = stdin_args.playlist
        else:
            year, month, day = self.list_date.split('-')
            self.json_file = os.path.join(
             _playlist.path, year, month, self.list_date + '.json')

        if '://' in self.json_file:
            self.json_file = self.json_file.replace('\\', '/')

            try:
                req = request.urlopen(self.json_file,
                                      timeout=1,
                                      context=ssl._create_unverified_context())
                b_time = req.headers['last-modified']
                temp_time = time.strptime(b_time, "%a, %d %b %Y %H:%M:%S %Z")
                mod_time = time.mktime(temp_time)

                if mod_time > self.last_mod_time:
                    self.clip_nodes = valid_json(req)
                    self.last_mod_time = mod_time
                    messenger.info('Open: ' + self.json_file)
                    validate_thread(self.clip_nodes)
            except (request.URLError, socket.timeout):
                self.eof_handling('Get playlist from url failed!', False)

        elif os.path.isfile(self.json_file):
            # check last modification from playlist
            mod_time = os.path.getmtime(self.json_file)
            if mod_time > self.last_mod_time:
                with open(self.json_file, 'r', encoding='utf-8') as f:
                    self.clip_nodes = valid_json(f)

                self.last_mod_time = mod_time
                messenger.info('Open: ' + self.json_file)
                validate_thread(self.clip_nodes)
        else:
            # when we have no playlist for the current day,
            # then we generate a black clip
            # and calculate the seek in time, for when the playlist comes back
            self.eof_handling('Playlist not exist:', False)