Python time.split() Examples

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

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

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

Example 1
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
    """
    Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.

    @type qs: C{bytes}
    """
    d = {}
    items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
    for item in items:
        try:
            k, v = item.split(b"=", 1)
        except ValueError:
            if strict_parsing:
                raise
            continue
        if v or keep_blank_values:
            k = unquote(k.replace(b"+", b" "))
            v = unquote(v.replace(b"+", b" "))
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    return d 
Example 2
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def fromChunk(data):
    """
    Convert chunk to string.

    @type data: C{bytes}

    @return: tuple of (result, remaining) - both C{bytes}.

    @raise ValueError: If the given data is not a correctly formatted chunked
        byte string.
    """
    prefix, rest = data.split(b'\r\n', 1)
    length = int(prefix, 16)
    if length < 0:
        raise ValueError("Chunk length must be >= 0, not %d" % (length,))
    if rest[length:length + 2] != b'\r\n':
        raise ValueError("chunk must end with CRLF")
    return rest[:length], rest[length + 2:] 
Example 3
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def parseContentRange(header):
    """
    Parse a content-range header into (start, end, realLength).

    realLength might be None if real length is not known ('*').
    """
    kind, other = header.strip().split()
    if kind.lower() != "bytes":
        raise ValueError("a range of type %r is not supported")
    startend, realLength = other.split("/")
    start, end = map(int, startend.split("-"))
    if realLength == "*":
        realLength = None
    else:
        realLength = int(realLength)
    return (start, end, realLength) 
Example 4
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def parseCookies(self):
        """
        Parse cookie headers.

        This method is not intended for users.
        """
        cookieheaders = self.requestHeaders.getRawHeaders(b"cookie")

        if cookieheaders is None:
            return

        for cookietxt in cookieheaders:
            if cookietxt:
                for cook in cookietxt.split(b';'):
                    cook = cook.lstrip()
                    try:
                        k, v = cook.split(b'=', 1)
                        self.received_cookies[k] = v
                    except ValueError:
                        pass 
Example 5
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getRequestHostname(self):
        """
        Get the hostname that the user passed in to the request.

        This will either use the Host: header (if it is available) or the
        host we are listening on if the header is unavailable.

        @returns: the requested hostname
        @rtype: C{bytes}
        """
        # XXX This method probably has no unit tests.  I changed it a ton and
        # nothing failed.
        host = self.getHeader(b'host')
        if host:
            return host.split(b':', 1)[0]
        return networkString(self.getHost().host) 
Example 6
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _authorize(self):
        # Authorization, (mostly) per the RFC
        try:
            authh = self.getHeader(b"Authorization")
            if not authh:
                self.user = self.password = ''
                return
            bas, upw = authh.split()
            if bas.lower() != b"basic":
                raise ValueError()
            upw = base64.decodestring(upw)
            self.user, self.password = upw.split(b':', 1)
        except (binascii.Error, ValueError):
            self.user = self.password = ""
        except:
            log.err()
            self.user = self.password = "" 
Example 7
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
    """
    Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.

    @type qs: C{bytes}
    """
    d = {}
    items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
    for item in items:
        try:
            k, v = item.split(b"=", 1)
        except ValueError:
            if strict_parsing:
                raise
            continue
        if v or keep_blank_values:
            k = unquote(k.replace(b"+", b" "))
            v = unquote(v.replace(b"+", b" "))
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    return d 
Example 8
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def fromChunk(data):
    """
    Convert chunk to string.

    @type data: C{bytes}

    @return: tuple of (result, remaining) - both C{bytes}.

    @raise ValueError: If the given data is not a correctly formatted chunked
        byte string.
    """
    prefix, rest = data.split(b'\r\n', 1)
    length = int(prefix, 16)
    if length < 0:
        raise ValueError("Chunk length must be >= 0, not %d" % (length,))
    if rest[length:length + 2] != b'\r\n':
        raise ValueError("chunk must end with CRLF")
    return rest[:length], rest[length + 2:] 
Example 9
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def parseContentRange(header):
    """
    Parse a content-range header into (start, end, realLength).

    realLength might be None if real length is not known ('*').
    """
    kind, other = header.strip().split()
    if kind.lower() != "bytes":
        raise ValueError("a range of type %r is not supported")
    startend, realLength = other.split("/")
    start, end = map(int, startend.split("-"))
    if realLength == "*":
        realLength = None
    else:
        realLength = int(realLength)
    return (start, end, realLength) 
Example 10
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def parseCookies(self):
        """
        Parse cookie headers.

        This method is not intended for users.
        """
        cookieheaders = self.requestHeaders.getRawHeaders(b"cookie")

        if cookieheaders is None:
            return

        for cookietxt in cookieheaders:
            if cookietxt:
                for cook in cookietxt.split(b';'):
                    cook = cook.lstrip()
                    try:
                        k, v = cook.split(b'=', 1)
                        self.received_cookies[k] = v
                    except ValueError:
                        pass 
Example 11
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def getRequestHostname(self):
        """
        Get the hostname that the user passed in to the request.

        This will either use the Host: header (if it is available) or the
        host we are listening on if the header is unavailable.

        @returns: the requested hostname
        @rtype: C{bytes}
        """
        # XXX This method probably has no unit tests.  I changed it a ton and
        # nothing failed.
        host = self.getHeader(b'host')
        if host:
            return host.split(b':', 1)[0]
        return networkString(self.getHost().host) 
Example 12
Project: learn_python3_spider   Author: wistbean   File: http.py    License: MIT License 6 votes vote down vote up
def _authorize(self):
        # Authorization, (mostly) per the RFC
        try:
            authh = self.getHeader(b"Authorization")
            if not authh:
                self.user = self.password = ''
                return
            bas, upw = authh.split()
            if bas.lower() != b"basic":
                raise ValueError()
            upw = base64.decodestring(upw)
            self.user, self.password = upw.split(b':', 1)
        except (binascii.Error, ValueError):
            self.user = self.password = ""
        except:
            self._log.failure('')
            self.user = self.password = "" 
Example 13
Project: DataMiningCompetitionFirstPrize   Author: lzddzh   File: consume_rank_feature.py    License: MIT License 6 votes vote down vote up
def extract_consume_per_person(file_name, consume_dict):
    lines = open(file_name).readlines()
    for line in lines:
        temps = line.strip("\r\n").split("$")
        id = temps[0]
        totol_amount = 0
        active_date_set = set()

        for i in range(1, len(temps)):
            records = temps[i].split(",")
            cate = records[0].strip("\"")
            amount = float(records[4].strip("\""))
            time = records[3].strip("\"")
            date = time.split(" ")[0]
            active_date_set.add(date)
            if cate == "POS消费":
                totol_amount += amount
        consume_dict[id] = float(totol_amount) / len(active_date_set) 
Example 14
Project: DataMiningCompetitionFirstPrize   Author: lzddzh   File: consume_rank_feature.py    License: MIT License 6 votes vote down vote up
def extract_rank_feature(file_name, final_rank, score_dict, if_train):
    if if_train:
        w = open("../original_data/rank_feature_train.txt", 'w')
    else:
        w = open("../original_data/rank_feature_test.txt", 'w')

    lines = open(file_name).readlines()
    for line in lines:
        if if_train:
            id = line.strip().split(",")[0]
        else:
            id = line.strip()
            print id
        w.write("{")
        w.write('"stuId": ' + id + ", ")

        if score_dict.has_key(id) and final_rank.has_key(id):
            w.write('"rank_in_faculty":' + str(final_rank[id]) + "," + '"rank_score_consume":' + str(
                final_rank[id] * score_dict[id]) + "} \n")
        else:
            w.write(
                '"rank_in_faculty":' + str(final_rank.get(id, -999)) + "," + '"rank_score_consume":' + str(
                    -999) + "} \n")

    w.close() 
Example 15
Project: Attendace_management_system   Author: Spidy20   File: AMS_Run.py    License: MIT License 6 votes vote down vote up
def getImagesAndLabels(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    # create empth face list
    faceSamples = []
    # create empty ID list
    Ids = []
    # now looping through all the image paths and loading the Ids and the images
    for imagePath in imagePaths:
        # loading the image and converting it to gray scale
        pilImage = Image.open(imagePath).convert('L')
        # Now we are converting the PIL image into numpy array
        imageNp = np.array(pilImage, 'uint8')
        # getting the Id from the image

        Id = int(os.path.split(imagePath)[-1].split(".")[1])
        # extract the face from the training image sample
        faces = detector.detectMultiScale(imageNp)
        # If a face is there then append that in the list as well as Id of it
        for (x, y, w, h) in faces:
            faceSamples.append(imageNp[y:y + h, x:x + w])
            Ids.append(Id)
    return faceSamples, Ids 
Example 16
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def get_app_pid(self, packageName):
        """
        获取进程pid
        args:
        - packageName -: 应用包名
        usage: getPid("com.android.settings")
        """
        if self.system is "Windows":
            pidinfo = self.shell("ps | findstr %s$" % packageName).stdout.read()
        else:
            pidinfo = self.shell("ps | grep -w %s" % packageName).stdout.read()

        if pidinfo == '':
            return "the process doesn't exist."

        pattern = re.compile(r"\d+")
        result = pidinfo.split(" ")
        result.remove(result[0])

        return  pattern.findall(" ".join(result))[0] 
Example 17
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def get_battery_status(self):
        """
        获取电池充电状态
        BATTERY_STATUS_UNKNOWN:未知状态
        BATTERY_STATUS_CHARGING: 充电状态
        BATTERY_STATUS_DISCHARGING: 放电状态
        BATTERY_STATUS_NOT_CHARGING:未充电
        BATTERY_STATUS_FULL: 充电已满
        """
        statusDict = {1 : "BATTERY_STATUS_UNKNOWN",
                      2 : "BATTERY_STATUS_CHARGING",
                      3 : "BATTERY_STATUS_DISCHARGING",
                      4 : "BATTERY_STATUS_NOT_CHARGING",
                      5 : "BATTERY_STATUS_FULL"}
        status = self.shell("dumpsys battery | %s status" %self.find_type).stdout.read().split(": ")[-1]

        return statusDict[int(status)] 
Example 18
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def do_send_text(self, string):
        """
        发送一段文本,只能包含英文字符和空格,多个空格视为一个空格
        usage: sendText("i am unique")
        """
        text = str(string).split(" ")
        out = []
        for i in text:
            if i != "":
                out.append(i)
        length = len(out)
        for i in xrange(length):
            self.shell("input text %s" % out[i])
            if i != length - 1:
                self.sendKeyEvent(EventKeys.SPACE)
        time.sleep(0.5) 
Example 19
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def do_stop_and_restart_5037(self):
        pid1 = os.popen("netstat -ano | findstr 5037 | findstr  LISTENING").read()
        if pid1 is not None:
            pid = pid1.split()[-1]
        # 下面的命令执行结果,可能因电脑而异,若获取adb.exe时出错,可自行调试!
        # E:\>tasklist /FI "PID eq 10200"
        # Image Name                     PID Session Name        Session#    Mem Usage
        # ========================= ======== ================ =========== ============
        # adb.exe                      10200 Console                    1      6,152 K

        process_name = os.popen('tasklist /FI "PID eq %s"' %pid).read().split()[-6]
        process_path = os.popen('wmic process where name="%s" get executablepath' %process_name).read().split("\r\n")[1]

        # #分割路径,得到进程所在文件夹名
        # name_list = process_path.split("\\")
        # del name_list[-1]
        # directory = "\\".join(name_list)
        # #打开进程所在文件夹
        # os.system("explorer.exe %s" %directory)
        # 杀死该进程
        os.system("taskkill /F /PID %s" %pid)
        os.system("adb start-server") 
Example 20
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def get_crash_log(self):
        # 获取app发生crash的时间列表
        time_list = []
        result_list = self.shell("dumpsys dropbox | findstr data_app_crash").stdout.readlines()
        for time in result_list:
            temp_list = time.split(" ")
            temp_time= []
            temp_time.append(temp_list[0])
            temp_time.append(temp_list[1])
            time_list.append(" ".join(temp_time))

        if time_list is None or len(time_list) <= 0:
            print ">>>No crash log to get"
            return None
        log_file = "T://Exception_log_%s.txt" % self.timestamp()
        f = open(log_file, "wb")
        for timel in time_list:
            cash_log = self.shell(timel).stdout.read()
            f.write(cash_log)
        f.close()
        print ">>>check local file" 
Example 21
Project: AppiumTestProject   Author: gitjayzhen   File: AdbCommand.py    License: Apache License 2.0 6 votes vote down vote up
def get_permission_list(self, package_name):
        PATH = lambda p: os.path.abspath(p)
        permission_list = []
        result_list = self.shell("dumpsys package %s | findstr android.permission" %package_name).stdout.readlines()
        for permission in result_list:
            permission_list.append(permission.strip())
        pwd = os.path.join(os.getcwd(),"gui_controller\\scriptUtils")
        permission_json_file = file("%s\\permission.json"%pwd)
        file_content = json.load(permission_json_file)["PermissList"]
        name = "_".join(package_name.split("."))
        f = open(PATH("%s\\%s_permission.txt" %(pwd,name)), "w")
        f.write("package: %s\n\n" %package_name)
        for permission in permission_list:
            for permission_dict in file_content:
                if permission == permission_dict["Key"]:
                    f.write(permission_dict["Key"] + ":\n  " + permission_dict["Memo"] + "\n")
        f.close 
Example 22
Project: SunFounder_SensorKit_for_RPi2   Author: sunfounder   File: 33_ds1302.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setup():
	print ('')
	print ('')
	print (rtc.get_datetime())
	print ('')
	print ('')
	a = input( "Do you want to setup date and time?(y/n) ")
	if a == 'y' or a == 'Y':
		date = input("Input date:(YYYY MM DD) ")
		time = input("Input time:(HH MM SS) ")
		date = list(map(lambda x: int(x), date.split()))
		time = list(map(lambda x: int(x), time.split()))
		print ('')
		print ('')
		rtc.set_datetime(datetime(date[0], date[1], date[2], time[0], time[1], time[2]))
		dt = rtc.get_datetime()
		print ("You set the date and time to:", dt) 
Example 23
Project: python-for-android   Author: kuri65536   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, unquote=unquote):
    """
    like cgi.parse_qs, only with custom unquote function
    """
    d = {}
    items = [s2 for s1 in qs.split("&") for s2 in s1.split(";")]
    for item in items:
        try:
            k, v = item.split("=", 1)
        except ValueError:
            if strict_parsing:
                raise
            continue
        if v or keep_blank_values:
            k = unquote(k.replace("+", " "))
            v = unquote(v.replace("+", " "))
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    return d 
Example 24
Project: python-for-android   Author: kuri65536   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def parseContentRange(header):
    """
    Parse a content-range header into (start, end, realLength).

    realLength might be None if real length is not known ('*').
    """
    kind, other = header.strip().split()
    if kind.lower() != "bytes":
        raise ValueError, "a range of type %r is not supported"
    startend, realLength = other.split("/")
    start, end = map(int, startend.split("-"))
    if realLength == "*":
        realLength = None
    else:
        realLength = int(realLength)
    return (start, end, realLength) 
Example 25
Project: python-for-android   Author: kuri65536   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def parseCookies(self):
        """
        Parse cookie headers.

        This method is not intended for users.
        """
        cookieheaders = self.requestHeaders.getRawHeaders("cookie")

        if cookieheaders is None:
            return

        for cookietxt in cookieheaders:
            if cookietxt:
                for cook in cookietxt.split(';'):
                    cook = cook.lstrip()
                    try:
                        k, v = cook.split('=', 1)
                        self.received_cookies[k] = v
                    except ValueError:
                        pass 
Example 26
Project: python-for-android   Author: kuri65536   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def getRequestHostname(self):
        """
        Get the hostname that the user passed in to the request.

        This will either use the Host: header (if it is available) or the
        host we are listening on if the header is unavailable.

        @returns: the requested hostname
        @rtype: C{str}
        """
        # XXX This method probably has no unit tests.  I changed it a ton and
        # nothing failed.
        host = self.getHeader('host')
        if host:
            return host.split(':', 1)[0]
        return self.getHost().host 
Example 27
Project: BitTorrent   Author: kenorb-contrib   File: http.py    License: GNU General Public License v3.0 6 votes vote down vote up
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, unquote=unquote):
    """like cgi.parse_qs, only with custom unquote function"""
    d = {}
    items = [s2 for s1 in qs.split("&") for s2 in s1.split(";")]
    for item in items:
        try:
            k, v = item.split("=", 1)
        except ValueError:
            if strict_parsing:
                raise
            continue
        if v or keep_blank_values:
            k = unquote(k.replace("+", " "))
            v = unquote(v.replace("+", " "))
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    return d 
Example 28
Project: BitTorrent   Author: kenorb-contrib   File: http.py    License: GNU General Public License v3.0 6 votes vote down vote up
def lineReceived(self, line):
        if self.firstLine:
            self.firstLine = 0
            l = line.split(None, 2)
            version = l[0]
            status = l[1]
            try:
                message = l[2]
            except IndexError:
                # sometimes there is no message
                message = ""
            self.handleStatus(version, status, message)
            return
        if line:
            key, val = line.split(':', 1)
            val = val.lstrip()
            self.handleHeader(key, val)
            if key.lower() == 'content-length':
                self.length = int(val)
        else:
            self.__buffer = StringIO()
            self.handleEndHeaders()
            self.setRawMode() 
Example 29
Project: persepolis   Author: persepolisdm   File: download.py    License: GNU General Public License v3.0 5 votes vote down vote up
def sigmaTime(time):
    hour, minute = time.split(":")
    return (int(hour)*60 + int(minute))

# nowTime returns now time in HH:MM format! 
Example 30
Project: Safejumper-for-Desktop   Author: proxysh   File: http.py    License: GNU General Public License v2.0 5 votes vote down vote up
def extractHeader(self, header):
        """
        Given a complete HTTP header, extract the field name and value and
        process the header.

        @param header: a complete HTTP request header of the form
            'field-name: value'.
        @type header: C{bytes}
        """
        key, val = header.split(b':', 1)
        val = val.lstrip()
        self.handleHeader(key, val)
        if key.lower() == b'content-length':
            self.length = int(val)