本文整理汇总了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,
)
示例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)
示例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()
示例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
示例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'
示例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
示例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"
示例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)
示例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
示例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---------------------
示例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
示例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)))
示例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
示例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)
示例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,
)