Python time.strptime() Examples

The following are 30 code examples of time.strptime(). 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 time , or try the search function .
Example #1
Source File: cookies.py    From vulscan with 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 #2
Source File: predict_spending_rough.py    From kaggle-code with MIT License 6 votes vote down vote up
def parseDateCol(df, date_col):
	""" takes the date column and adds new columns with the features:
		yr, mon, day, day of week, day of year """
	df['datetime'] = df.apply(lambda x : time.strptime(str(x[date_col]),  "%Y%M%d"), axis = 1)
	print('parsing year')
	df['year'] = df.apply(lambda x : x['datetime'].tm_year, axis = 1)
	print('parsing month')
	df['month'] = df.apply(lambda x :x['datetime'].tm_mon , axis = 1)
	print('parsing days (*3 versions)')
	df['mday'] = df.apply(lambda x : x['datetime'].tm_mday, axis = 1)
	df['wday'] = df.apply(lambda x : x['datetime'].tm_wday , axis = 1)
	df['yday'] = df.apply(lambda x : x['datetime'].tm_yday , axis = 1)

	#drop date and datetime
	df = df.drop([date_col, 'datetime'], axis = 1)
	
	return df 
Example #3
Source File: test_loggers.py    From moler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiline_formatter_puts_message_lines_into_data_area():
    """
    We want logs to look like:

    01 19:36:09.823  |This is
                     |multiline
                     |content
    """
    from moler.config.loggers import MultilineWithDirectionFormatter

    formatter = MultilineWithDirectionFormatter(fmt="%(asctime)s.%(msecs)03d |%(message)s", datefmt="%d %H:%M:%S")
    tm_struct = time.strptime("2000-01-01 19:36:09", "%Y-%m-%d %H:%M:%S")
    epoch_tm = time.mktime(tm_struct)
    logging_time = epoch_tm
    log_rec = logging.makeLogRecord({'msg': "This is\nmultiline\ncontent",
                                     'created': logging_time, 'msecs': 823})
    output = formatter.format(log_rec)

    assert output == "01 19:36:09.823 |This is\n" \
                     "                |multiline\n" \
                     "                |content" 
Example #4
Source File: test_unit_datetime.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_struct_time_format():
    # struct_time for general use
    value = time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S")
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS.FF')
    assert formatter.format(value) == '2001-09-30T11:20:30.0'

    # struct_time encapsulated in SnowflakeDateTime. Mainly used by SnowSQL
    value = SnowflakeDateTime(
        time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S"),
        nanosecond=0, scale=1
    )
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS.FF',
        datetime_class=SnowflakeDateTime)
    assert formatter.format(value) == '2001-09-30T11:20:30.0'

    # format without fraction of seconds
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS',
        datetime_class=SnowflakeDateTime)
    assert formatter.format(value) == '2001-09-30T11:20:30' 
Example #5
Source File: dashboard.py    From EDMarketConnector with GNU General Public License v2.0 6 votes vote down vote up
def process(self, logfile=None):
        try:
            with open(join(self.currentdir, 'Status.json'), 'rb') as h:
                data = h.read().strip()
                if data:	# Can be empty if polling while the file is being re-written
                    entry = json.loads(data)

                    # Status file is shared between beta and live. So filter out status not in this game session.
                    if (timegm(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) >= self.session_start and
                        self.status != entry):
                        self.status = entry
                        self.root.event_generate('<<DashboardEvent>>', when="tail")
        except:
            if __debug__: print_exc()

# singleton 
Example #6
Source File: test_io.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dtype_with_object(self):
        # Test using an explicit dtype with an object
        data = """ 1; 2001-01-01
                   2; 2002-01-31 """
        ndtype = [('idx', int), ('code', object)]
        func = lambda s: strptime(s.strip(), "%Y-%m-%d")
        converters = {1: func}
        test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype,
                             converters=converters)
        control = np.array(
            [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
            dtype=ndtype)
        assert_equal(test, control)

        ndtype = [('nest', [('idx', int), ('code', object)])]
        with assert_raises_regex(NotImplementedError,
                                 'Nested fields.* not supported.*'):
            test = np.genfromtxt(TextIO(data), delimiter=";",
                                 dtype=ndtype, converters=converters) 
Example #7
Source File: controller.py    From genmon with GNU General Public License v2.0 6 votes vote down vote up
def GetPowerLogForMinutes(self, Minutes = 0):
        try:
            ReturnList = []
            PowerList = self.ReadPowerLogFromFile()
            if not Minutes:
                return PowerList
            CurrentTime = datetime.datetime.now()

            for Time, Power in reversed(PowerList):
                struct_time = time.strptime(Time, "%x %X")
                LogEntryTime = datetime.datetime.fromtimestamp(time.mktime(struct_time))
                Delta = CurrentTime - LogEntryTime
                if self.GetDeltaTimeMinutes(Delta) < Minutes :
                    ReturnList.insert(0, [Time, Power])
            return ReturnList
        except Exception as e1:
            self.LogErrorLine("Error in GetPowerLogForMinutes: " + str(e1))
            return ReturnList

    #------------ GeneratorController::ReadPowerLogFromFile--------------------- 
Example #8
Source File: backtracking.py    From PT-help with MIT License 6 votes vote down vote up
def backtracking_id(site):
    cookies = cookies_raw2jar(site['cookies'])
    for _tid in range(site['start_torrent'], site['end_torrent'] + 2):
        t0 = time.time()

        _link = site['torrent_url'].format(_tid)
        torrent_page = requests.get(_link, cookies=cookies, headers=headers)
        title_search = re.search(site['search_ptn'], torrent_page.text)

        if title_search:
            _title = pymysql.escape_string(unescape(title_search.group("title")))
            pubDate = re.search("发布于(.+?)<", torrent_page.text).group(1)
            _timestamp = time.mktime(time.strptime(pubDate, "%Y-%m-%d %H:%M:%S"))

            wrap_insert(site=site['name'], sid=_tid, title=_title, link=_link, pubdate=_timestamp, t=t0)
        else:
            print("ID: {}, Cost: {:.5f} s, No torrent.".format(_tid, time.time() - t0))

        time.sleep(2) 
Example #9
Source File: test_unit_datetime.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_struct_time_format():
    # struct_time for general use
    value = time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S")
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS.FF')
    assert formatter.format(value) == '2001-09-30T11:20:30.0'

    # struct_time encapsulated in SnowflakeDateTime. Mainly used by SnowSQL
    value = SnowflakeDateTime(
        time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S"),
        nanosecond=0, scale=1
    )
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS.FF',
        datetime_class=SnowflakeDateTime)
    assert formatter.format(value) == '2001-09-30T11:20:30.0'

    # format without fraction of seconds
    formatter = SnowflakeDateTimeFormat(
        'YYYY-MM-DD"T"HH24:MI:SS',
        datetime_class=SnowflakeDateTime)
    assert formatter.format(value) == '2001-09-30T11:20:30' 
Example #10
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 #11
Source File: clean_to_np_matrix.py    From kaggle-code with MIT License 6 votes vote down vote up
def parseDateCol(df, date_col):
	""" takes the date column and adds new columns with the features:
		yr, mon, day, day of week, day of year """
	df['datetime'] = df.apply(lambda x : time.strptime(str(x[date_col]),  "%Y%M%d"), axis = 1)
	print('parsing year')
	df['year'] = df.apply(lambda x : x['datetime'].tm_year, axis = 1)
	print('parsing month')
	df['month'] = df.apply(lambda x :x['datetime'].tm_mon , axis = 1)
	print('parsing days (*3 versions)')
	df['mday'] = df.apply(lambda x : x['datetime'].tm_mday, axis = 1)
	df['wday'] = df.apply(lambda x : x['datetime'].tm_wday , axis = 1)
	df['yday'] = df.apply(lambda x : x['datetime'].tm_yday , axis = 1)

	#drop date and datetime
	df = df.drop([date_col, 'datetime'], axis = 1)
	
	return df 
Example #12
Source File: cookies.py    From jawfish with 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
Source File: mysqlite.py    From GithubMonitor with MIT License 6 votes vote down vote up
def _get_hour():
    '''
    返回上个小时的时间戳
    假如现在是 2018.11.21 19:44:02, 那么返回 '1542794400'
    即 2018.11.21 18:00:00 的时间戳

    返回值:
        字符串;上个小时的时间戳
    '''

    return int(
        time.mktime(
            time.strptime(
                time.strftime("%Y-%m-%d %H"), "%Y-%m-%d %H")
        )
    )-3600 
Example #14
Source File: reader.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def parse_init_dt(self, arg_from, tail_dt):
        if arg_from.startswith("-"):
            # Relative start time:
            try:
                init_dt = tail_dt - self.parse_timedelta(arg_from.strip("- "))
            except Exception:
                self.logger.warning(
                    "Ignoring relative start time. Can't parse relative start time " + arg_from)
                return 0
        else:
            # Absolute start time:
            try:
                init_dt = datetime.datetime(
                    *(time.strptime(arg_from, DT_FMT)[0:6]))
            except Exception as e:
                self.logger.warning(
                    "Ignoring absolute start time. Can't parse absolute start time " + arg_from + " " + str(e))
                return 0
        return init_dt 
Example #15
Source File: parsetime.py    From Jtyoui with MIT License 6 votes vote down vote up
def change_time(self, day=0, hour=0, minute=0, week=0, second=0):
        """增加天数来修改时间"""
        add_time = datetime.timedelta(days=day, hours=hour, minutes=minute, weeks=week, seconds=second)
        if self.reduction:
            change = F'{self.now_year}-{self.now_mon}-{self.now_day} 00:00:00'  # 时分秒还原到0
            self.reduction = False
        else:
            change = self.str_time()
        add = datetime.datetime.strptime(change, self.format) + add_time
        self.now_year = add.year
        self.now_mon = add.month
        self.now_day = add.day
        self.now_hour = add.hour
        self.now_minute = add.minute
        self.now_second = add.second
        self.now_week = add.isoweekday() 
Example #16
Source File: test_io.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_converters_cornercases2(self):
        # Test the conversion to datetime64.
        converter = {
            'date': lambda s: np.datetime64(strptime(s, '%Y-%m-%d %H:%M:%SZ'))}
        data = TextIO('2009-02-03 12:00:00Z, 72214.0')
        test = np.ndfromtxt(data, delimiter=',', dtype=None,
                            names=['date', 'stid'], converters=converter)
        control = np.array((datetime(2009, 2, 3), 72214.),
                           dtype=[('date', 'datetime64[us]'), ('stid', float)])
        assert_equal(test, control) 
Example #17
Source File: controller.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def ValidateMaintLogEntry(self, Entry):

        try:
            # add_maint_log={"date":"01/02/2019 14:59", "type":"Repair", "comment":"Hello"}
            if not isinstance(Entry, dict):
                self.LogError("Error in ValidateMaintLogEntry: Entry is not a dict")
                return False

            if not isinstance(Entry["date"], str) and not isinstance(Entry["date"], unicode):
                self.LogError("Error in ValidateMaintLogEntry: Entry date is not a string: " + str(type(Entry["date"])))
                return False

            try:
                EntryDate = datetime.datetime.strptime(Entry["date"], "%m/%d/%Y %H:%M")
            except Exception as e1:
                self.LogErrorLine("Error in ValidateMaintLogEntry: expecting MM/DD/YYYY : " + str(e1))

            if not isinstance(Entry["type"], str) and not isinstance(Entry["type"], unicode):
                self.LogError("Error in ValidateMaintLogEntry: Entry type is not a string: " + str(type(Entry["hours"])))
                return False
            if not Entry["type"].lower() in ["maintenance", "check", "repair", "observation"]:
                self.LogError("Error in ValidateMaintLogEntry: Invalid type: " + str(Entry["type"]))

            Entry["type"] = Entry["type"].title()

            if not isinstance(Entry["hours"], int) and not isinstance(Entry["hours"], float) :
                self.LogError("Error in ValidateMaintLogEntry: Entry type is not a number: " + str(type(Entry["hours"])))
                return False
            if not isinstance(Entry["comment"], str) and not isinstance(Entry["comment"], unicode):
                self.LogError("Error in ValidateMaintLogEntry: Entry comment is not a string: " + str(type(Entry["comment"])))

        except Exception as e1:
            self.LogErrorLine("Error in ValidateMaintLogEntry: " + str(e1))
            return False

        return True
    #----------  GeneratorController::GetMaintLog------------------------------- 
Example #18
Source File: cookies.py    From recruit with Apache License 2.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 #19
Source File: controller.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def GetAveragePower(self, PowerList):

        try:
            TotalTime = datetime.timedelta(seconds=0)
            Entries = 0
            TotalPower = 0.0
            LastPower = 0.0
            LastTime = None
            for Items in PowerList:
                Power = float(Items[1])
                struct_time = time.strptime(Items[0], "%x %X")
                LogEntryTime = datetime.datetime.fromtimestamp(time.mktime(struct_time))

                if LastTime != None:
                    if LogEntryTime > LastTime:
                        self.LogError("Error in GetAveragePower: time sequence error")

                if LastTime == None or Power == 0:
                    TotalTime += LogEntryTime - LogEntryTime
                else:
                    TotalTime += LastTime - LogEntryTime
                    TotalPower += (Power + LastPower) / 2
                    Entries += 1
                LastTime = LogEntryTime
                LastPower = Power

            if Entries == 0:
                return 0,0
            TotalPower = TotalPower / Entries
            return TotalPower, TotalTime.total_seconds()
        except Exception as e1:
            self.LogErrorLine("Error in  GetAveragePower: " + str(e1))
            return 0, 0

    #----------  GeneratorController::PowerMeter--------------------------------
    #----------  Monitors Power Output 
Example #20
Source File: cookies.py    From NEIE-Assistant 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 #21
Source File: utils.py    From ssh-ca with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_time(time_string, reference_time=int(time.time())):
    """Parses a time in YYYYMMDDHHMMSS or +XXXX[smhdw][...]

    Returns epoch time.  Just like ssk-keygen, we allow complex
    expressions like +5d7h37m for 5 days, 7 hours, 37 minutes.

    reference_time should be the epoch time used for calculating
    the time when using +XXXX[smhdw][...], defaults to now.
    """

    seconds = 0
    if time_string[0] == '+' or time_string[0] == '-':
        # parse relative expressions
        sign = None
        number = ''
        factor = 's'
        for c in time_string:
            if not sign:
                sign = c
            elif c.isdigit():
                number = number + c
            else:
                factor = c
                seconds += convert_relative_time(
                    "%s%s%s" % (sign, number, factor))
                number = ''
                factor = 's'

        # per ssh-keygen, if specifing seconds, then the 's' is not required
        if len(number) > 0:
            seconds += convert_relative_time("%s%ss" % (sign, number))

        epoch = seconds + reference_time

    else:
        # parse YYYYMMDDHHMMSS
        struct_time = time.strptime(time_string, "%Y%m%d%H%M%S")
        epoch = int(time.mktime(struct_time))

    return epoch 
Example #22
Source File: test_io.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_converters_cornercases(self):
        # Test the conversion to datetime.
        converter = {
            'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}
        data = TextIO('2009-02-03 12:00:00Z, 72214.0')
        test = np.ndfromtxt(data, delimiter=',', dtype=None,
                            names=['date', 'stid'], converters=converter)
        control = np.array((datetime(2009, 2, 3), 72214.),
                           dtype=[('date', np.object_), ('stid', float)])
        assert_equal(test, control) 
Example #23
Source File: test_io.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dtype_with_object(self):
        # Test using an explicit dtype with an object
        data = """ 1; 2001-01-01
                   2; 2002-01-31 """
        ndtype = [('idx', int), ('code', object)]
        func = lambda s: strptime(s.strip(), "%Y-%m-%d")
        converters = {1: func}
        test = np.loadtxt(TextIO(data), delimiter=";", dtype=ndtype,
                          converters=converters)
        control = np.array(
            [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
            dtype=ndtype)
        assert_equal(test, control) 
Example #24
Source File: test_io.py    From recruit with Apache License 2.0 5 votes vote down vote up
def strptime(s, fmt=None):
    """
    This function is available in the datetime module only from Python >=
    2.5.

    """
    if type(s) == bytes:
        s = s.decode("latin1")
    return datetime(*time.strptime(s, fmt)[:3]) 
Example #25
Source File: test_loggers.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multiline_formatter_puts_direction_info_into_direction_area():
    """
    We want logs to look like:

    01 19:36:09.823 >|sent
    01 19:36:09.823 <|received
    01 19:36:09.823  |just log
    """
    from moler.config.loggers import MultilineWithDirectionFormatter

    formatter = MultilineWithDirectionFormatter(fmt="%(asctime)s.%(msecs)03d %(transfer_direction)s|%(message)s",
                                                datefmt="%d %H:%M:%S")
    tm_struct = time.strptime("2000-01-01 19:36:09", "%Y-%m-%d %H:%M:%S")
    epoch_tm = time.mktime(tm_struct)
    logging_time = epoch_tm

    log_rec = logging.makeLogRecord({'msg': "sent",
                                     'created': logging_time, 'msecs': 823,
                                     'transfer_direction': '>'})
    output = formatter.format(log_rec)
    assert output == "01 19:36:09.823 >|sent"

    log_rec = logging.makeLogRecord({'msg': "received",
                                     'created': logging_time, 'msecs': 823,
                                     'transfer_direction': '<'})
    output = formatter.format(log_rec)
    assert output == "01 19:36:09.823 <|received"

    log_rec = logging.makeLogRecord({'msg': "just log",
                                     'created': logging_time, 'msecs': 823})
    output = formatter.format(log_rec)
    assert output == "01 19:36:09.823  |just log" 
Example #26
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 #27
Source File: connection_manager.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _get_last_used_server(self):

        servers = self.credentials.get_credentials()['Servers']

        if not len(servers):
            return

        try:
            servers.sort(key=lambda x: datetime.strptime(x['DateLastAccessed'], "%Y-%m-%dT%H:%M:%SZ"), reverse=True)
        except TypeError:
            servers.sort(key=lambda x: datetime(*(time.strptime(x['DateLastAccessed'], "%Y-%m-%dT%H:%M:%SZ")[0:6])), reverse=True)

        return servers[0] 
Example #28
Source File: connection_manager.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def get_available_servers(self):
        LOG.debug("Begin getAvailableServers")

        # Clone the credentials
        credentials = self.credentials.get_credentials()
        connect_servers = self._get_connect_servers(credentials)
        found_servers = self._find_servers(self._server_discovery())

        if not connect_servers and not found_servers and not credentials['Servers']: # back out right away, no point in continuing
            LOG.info("Found no servers")

            return list()

        servers = list(credentials['Servers'])
        self._merge_servers(servers, found_servers)
        self._merge_servers(servers, connect_servers)
        servers = self._filter_servers(servers, connect_servers)

        try:
            servers.sort(key=lambda x: datetime.strptime(x['DateLastAccessed'], "%Y-%m-%dT%H:%M:%SZ"), reverse=True)
        except TypeError:
            servers.sort(key=lambda x: datetime(*(time.strptime(x['DateLastAccessed'], "%Y-%m-%dT%H:%M:%SZ")[0:6])), reverse=True)

        credentials['Servers'] = servers
        self.credentials.get_credentials(credentials)

        return servers 
Example #29
Source File: credentials.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _date_object(self, date):
        # Convert string to date
        try:
            date_obj = time.strptime(date, "%Y-%m-%dT%H:%M:%SZ")
        except (ImportError, TypeError):
            # TypeError: attribute of type 'NoneType' is not callable
            # Known Kodi/python error
            date_obj = datetime(*(time.strptime(date, "%Y-%m-%dT%H:%M:%SZ")[0:6]))
        
        return date_obj 
Example #30
Source File: cookies.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    )