当前位置: 首页>>代码示例>>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;未经允许,请勿转载。