當前位置: 首頁>>代碼示例>>Python>>正文


Python time.strptime方法代碼示例

本文整理匯總了Python中time.strptime方法的典型用法代碼示例。如果您正苦於以下問題:Python time.strptime方法的具體用法?Python time.strptime怎麽用?Python time.strptime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在time的用法示例。


在下文中一共展示了time.strptime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: morsel_to_cookie

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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,
    ) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:27,代碼來源:cookies.py

示例2: backtracking_id

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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) 
開發者ID:Rhilip,項目名稱:PT-help,代碼行數:21,代碼來源:backtracking.py

示例3: change_time

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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() 
開發者ID:jtyoui,項目名稱:Jtyoui,代碼行數:18,代碼來源:parsetime.py

示例4: parseDateCol

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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 
開發者ID:CNuge,項目名稱:kaggle-code,代碼行數:19,代碼來源:clean_to_np_matrix.py

示例5: test_struct_time_format

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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' 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:24,代碼來源:test_unit_datetime.py

示例6: _get_hour

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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 
開發者ID:Macr0phag3,項目名稱:GithubMonitor,代碼行數:18,代碼來源:mysqlite.py

示例7: test_multiline_formatter_puts_message_lines_into_data_area

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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" 
開發者ID:nokia,項目名稱:moler,代碼行數:23,代碼來源:test_loggers.py

示例8: test_dtype_with_object

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_io.py

示例9: process

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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 
開發者ID:EDCD,項目名稱:EDMarketConnector,代碼行數:18,代碼來源:dashboard.py

示例10: GetPowerLogForMinutes

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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--------------------- 
開發者ID:jgyates,項目名稱:genmon,代碼行數:22,代碼來源:controller.py

示例11: parse_init_dt

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:21,代碼來源:reader.py

示例12: to_unixtime

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def to_unixtime(time_string, format_string):
    with _STRPTIME_LOCK:
        return int(calendar.timegm(time.strptime(str(time_string), format_string))) 
開發者ID:jumpserver,項目名稱:jumpserver-python-sdk,代碼行數:5,代碼來源:utils.py

示例13: get_playlist

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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:
            self.clip_nodes = None 
開發者ID:ffplayout,項目名稱:ffplayout-engine,代碼行數:41,代碼來源:playlist.py

示例14: get_rebirth_time

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def get_rebirth_time() -> Tuple[int, time.struct_time]:
        """Get the current rebirth time.
        returns a namedtuple(days, timestamp) where days is the number
        of days displayed in the rebirth time text and timestamp is a
        time.struct_time object.
        """
        Rebirth_time = namedtuple('Rebirth_time', 'days timestamp')
        t = Inputs.ocr(*coords.OCR_REBIRTH_TIME)
        x = re.search(r"((?P<days>[0-9]+) days? )?((?P<hours>[0-9]+):)?(?P<minutes>[0-9]+):(?P<seconds>[0-9]+)", t)
        days = 0
        if x is None:
            timestamp = time.strptime("0:0:0", "%H:%M:%S")
        else:
            if x.group('days') is None:
                days = 0
            else:
                days = int(x.group('days'))
            
            if x.group('hours') is None:
                hours = "0"
            else:
                hours = x.group('hours')
            
            if x.group('minutes') is None:
                minutes = "0"
            else:
                minutes = x.group('minutes')
            
            if x.group('seconds') is None:
                seconds = "0"
            else:
                seconds = x.group('seconds')
            timestamp = time.strptime(f"{hours}:{minutes}:{seconds}", "%H:%M:%S")
        return Rebirth_time(days, timestamp) 
開發者ID:kujan,項目名稱:NGU-scripts,代碼行數:36,代碼來源:features.py

示例15: morsel_to_cookie

# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
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,
    ) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:31,代碼來源:cookies.py


注:本文中的time.strptime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。