本文整理匯總了Python中time.strptime方法的典型用法代碼示例。如果您正苦於以下問題:Python time.strptime方法的具體用法?Python time.strptime怎麽用?Python time.strptime使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊time的用法示例。
在下文中一共展示了time.strptime方法的20個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1: morsel_to_cookie
點讚 6
# 需要導入模塊: 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,
示例2: backtracking_id
點讚 6
# 需要導入模塊: 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("發布於(.+?)
_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,
示例3: change_time
點讚 6
# 需要導入模塊: 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,
示例4: parseDateCol
點讚 6
# 需要導入模塊: 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,
示例5: test_struct_time_format
點讚 6
# 需要導入模塊: 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,
示例6: _get_hour
點讚 6
# 需要導入模塊: 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,
示例7: test_multiline_formatter_puts_message_lines_into_data_area
點讚 6
# 需要導入模塊: 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,
示例8: test_dtype_with_object
點讚 6
# 需要導入模塊: 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,
示例9: process
點讚 6
# 需要導入模塊: 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('<>', when="tail")
except:
if __debug__: print_exc()
# singleton
開發者ID:EDCD,項目名稱:EDMarketConnector,代碼行數:18,
示例10: GetPowerLogForMinutes
點讚 6
# 需要導入模塊: 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,
示例11: parse_init_dt
點讚 6
# 需要導入模塊: 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,
示例12: to_unixtime
點讚 5
# 需要導入模塊: 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,
示例13: get_playlist
點讚 5
# 需要導入模塊: 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,
示例14: get_rebirth_time
點讚 5
# 需要導入模塊: 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[0-9]+) days? )?((?P[0-9]+):)?(?P[0-9]+):(?P[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,
示例15: morsel_to_cookie
點讚 5
# 需要導入模塊: 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,
示例16: timetuple
點讚 5
# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def timetuple(self):
return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
##
# Get date/time value.
#
# @return Date/time value, as an ISO 8601 string.
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:9,
示例17: _datetime_type
點讚 5
# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def _datetime_type(data):
return datetime.strptime(data, "%Y%m%dT%H:%M:%S")
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:10,
示例18: __init__
點讚 5
# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def __init__(self, data, current_date=None, date_format='%Y-%m-%d %H:%M:%S', **kwargs):
"""初始化數據日期
:param data: 當前數據
:param current_date: 當前日期
:param date_format: 日期解析格式
:param kwargs: 其他參數
- map_path: 解析日期的映射表
- re_path: 匹配日期的正則表
"""
# 加載日期的映射表和匹配日期的正則表
self.map, self.re = None, None
self.load_config(**kwargs)
self.data = data + '\033'
self._decide_ten()
# 定義當前日期
self.localtime = current_date if current_date else time.strftime(date_format)
self.format = date_format
# 將當前日期標準化
local = time.strptime(self.localtime, self.format)
# 初始化當前的年月日基本信息
self.now_year = local.tm_year
self.now_mon = local.tm_mon
self.now_day = local.tm_mday
self.now_week = local.tm_wday + 1
if current_date:
self.now_hour = local.tm_hour
self.now_minute = local.tm_min
self.now_second = local.tm_sec
else:
self.now_hour = 0
self.now_minute = 0
self.now_second = 0
self.reduction = True # 啟動還原時分秒
開發者ID:jtyoui,項目名稱:Jtyoui,代碼行數:41,
示例19: standard_time
點讚 5
# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def standard_time(self):
"""標準時間化"""
return time.strptime(self.str_time(), self.format)
開發者ID:jtyoui,項目名稱:Jtyoui,代碼行數:5,
示例20: __init__
點讚 5
# 需要導入模塊: import time [as 別名]
# 或者: from time import strptime [as 別名]
def __init__(self, sentence, date_str=None, date_format='%Y-%m-%d %H:%M:%S'):
"""傳入一個字符串時間和現在時間
:param sentence: 字符串時間
:param date_str: 你認為的現在時間,不傳默認是當前時間
:param date_format: 時間格式
"""
self._sentence = sentence
self._localtime = date_str if date_str else time.strftime(date_format)
self.format = date_format
self.local = time.strptime(self._localtime, self.format)
self.re_year = r'(今年)|(明年)|(後年)|(昨年)|(前年)|(去年)|(\d+年)'
self.re_mon = r'(上個?月)|(這個?月)|(下個?月)|(\d{0,2}本?月底?)|(\d*個?月以?後)'
self.re_day = r'(今天)|(明天)|(後天)|(昨天)|(前天)|(\d+日)|(\d+號)|(\d*天\w?[後前])'
self.re_week = r'(上個?周)|(下個?周)|(星期日)|(星期天)|(星期\d+)|(周\d+)'
self.re_hour = r'(早上)|(下午)|(晚上)|(\d+點)'
self.re_min = r'(\d+分)|(\d+點半)'
self.re_sec = r'(\d+秒)'
self.now_year = self.local.tm_year
self.now_mon = self.local.tm_mon
self.now_day = self.local.tm_mday
self.now_week = self.local.tm_wday + 1
self.chinese_numerals = copy.deepcopy(chinese_mon_number)
self.chinese_numerals.pop('十')
self.add_time = add_time
self.times = set()
開發者ID:jtyoui,項目名稱:Jtyoui,代碼行數:28,
注:本文中的time.strptime方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。