本文整理汇总了Python中datetime.strptime方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.strptime方法的具体用法?Python datetime.strptime怎么用?Python datetime.strptime使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime
的用法示例。
在下文中一共展示了datetime.strptime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: detect_date
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def detect_date(e):
if is_date(e): return True
for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
if isinstance(e, date_type): return True
# Slow!!!
# for date_format in DATE_FORMATS:
# try:
# if datetime.strptime(e, date_format):
# return True
# except:
# continue
# Also slow
# try:
# dparser.parse(e)
# return True
# except: pass
return False
示例2: testTimestampValue
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the XML output is valid.
Runs a test program that generates an empty XML output, and checks if
the timestamp attribute in the testsuites tag is valid.
"""
actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)
date_time_str = actual.documentElement.getAttributeNode('timestamp').value
# datetime.strptime() is only available in Python 2.5+ so we have to
# parse the expected datetime manually.
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
re.match,
'XML datettime string %s has incorrect format' % date_time_str)
date_time_from_xml = datetime.datetime(
year=int(match.group(1)), month=int(match.group(2)),
day=int(match.group(3)), hour=int(match.group(4)),
minute=int(match.group(5)), second=int(match.group(6)))
time_delta = abs(datetime.datetime.now() - date_time_from_xml)
# timestamp value should be near the current local time
self.assertTrue(time_delta < datetime.timedelta(seconds=600),
'time_delta is %s' % time_delta)
actual.unlink()
示例3: testTimestampValue
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the JSON output is valid.
Runs a test program that generates an empty JSON output, and checks if
the timestamp attribute in the testsuites tag is valid.
"""
actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)
date_time_str = actual['timestamp']
# datetime.strptime() is only available in Python 2.5+ so we have to
# parse the expected datetime manually.
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
re.match,
'JSON datettime string %s has incorrect format' % date_time_str)
date_time_from_json = datetime.datetime(
year=int(match.group(1)), month=int(match.group(2)),
day=int(match.group(3)), hour=int(match.group(4)),
minute=int(match.group(5)), second=int(match.group(6)))
time_delta = abs(datetime.datetime.now() - date_time_from_json)
# timestamp value should be near the current local time
self.assertTrue(time_delta < datetime.timedelta(seconds=600),
'time_delta is %s' % time_delta)
示例4: is_time_format
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def is_time_format(time):
"""
Check if 'time' variable has the format of one
of the 'time_formats'
"""
if time is None:
return False
for time_format in TIME_FORMATS:
try:
datetime.strptime(time, time_format)
return True
except ValueError:
pass
return False
示例5: withdraw
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def withdraw():
# send xbt withdrawal request
targetAddress = "xxxxxxxxxx"
currency = "xbt"
amount = 0.12345678
result = cfclient.send_withdrawal(targetAddress, currency, amount)
print("send_withdrawal:\n", result)
# get xbt transfers
lastTransferTime = datetime.datetime.strptime("2016-02-01", "%Y-%m-%d").isoformat() + ".000Z"
result = cfclient.get_transfers(lastTransferTime=lastTransferTime)
print("get_transfers:\n", result)
# transfer
fromAccount = "fi_ethusd"
toAccount = "cash"
unit = "eth"
amount = 0.1
result = cfclient.transfer(fromAccount, toAccount, unit, amount)
print("transfer:\n", result)
示例6: test
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def test(self):
cx = self.Symbol_Db['equity'].find()
symbolSet = set([d['code'] for d in cx])
for code in symbolSet:
start = self.Symbol_Db['equity'].find({"code" : code})[0]['timeToMarket']
try:
start = datetime.datetime.strptime(str(start), '%Y%m%d')
except :
print code
start = start.strftime("%Y-%m-%d")
print start
return
#----------------------------------------------------------------------
示例7: _triggerTime
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def _triggerTime(self):
'''检查定时触发'''
if not self._dataModel.getConfigModel().hasTimerTrigger() or not self.isRealTimeStatus():
return
nowTime = datetime.now()
for i,timeSecond in enumerate(self._dataModel.getConfigTimer()):
specifiedTime = datetime.strptime(timeSecond, "%H%M%S")
if 0<=(nowTime-specifiedTime).seconds<1 and not self._isTimeTriggered[i]:
self._isTimeTriggered[i] = True
key = self._dataModel.getConfigModel().getKLineShowInfoSimple()
dateTimeStamp, tradeDate, lv1Data = self.getTriggerTimeAndData(key[0])
event = Event({
"EventCode" : ST_TRIGGER_TIMER,
"ContractNo": None,
"KLineType" : None,
"KLineSlice": None,
"Data":{
"TradeDate": tradeDate,
"DateTimeStamp": dateTimeStamp,
"Data":timeSecond
}
})
self._triggerQueue.put(event)
示例8: feature2tile
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def feature2tile(cls, feature):
""" convert tile field attributes to tile identifier """
fldindex_h = feature.GetFieldIndex("h")
fldindex_v = feature.GetFieldIndex("v")
h = str(int(feature.GetField(fldindex_h))).zfill(2)
v = str(int(feature.GetField(fldindex_v))).zfill(2)
return "h%sv%s" % (h, v)
# @classmethod
# def find_dates(cls, tile):
# """ Get list of dates available in repository for a tile """
# tdir = cls.path(tile=tile)
# if os.path.exists(tdir):
# return [datetime.strptime(os.path.basename(d), cls._datedir).date() for d in os.listdir(tdir)]
# else:
# return []
示例9: get_total_seconds_from_epoch_for_fluent_logs
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def get_total_seconds_from_epoch_for_fluent_logs(self, datetime_string):
# fluentd logs timestamp format : 2018-08-02 19:27:34 +0000
# for python 2.7 or earlier there is no good way to convert it into seconds.
# so we parse upto seconds, and parse utc specific offset seperately.
try:
date_time_format = '%Y-%m-%d %H:%M:%S'
epoch = datetime(1970, 1, 1)
# get hours and minute delta for utc offset.
hours_delta_utc = int(datetime_string[21:23])
minutes_delta_utc= int(datetime_string[23:])
log_time = datetime.strptime(datetime_string[:19], date_time_format) + ((timedelta(hours=hours_delta_utc, minutes=minutes_delta_utc)) * (-1 if datetime_string[20] == "+" else 1))
return (log_time - epoch).total_seconds()
except Exception as e:
self._hutil_error('Error converting timestamp string to seconds. Exception={0}'.format(e))
return 0
示例10: filter_put
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def filter_put(mongodb, slug=None):
base()
data = request.json or {}
data['slug'] = slug
data = dict(data.items())
if 'lastupdate' in data and isinstance(data.get('lastupdate'), basestring):
data['lastupdate'] = datetime.strptime(data.get('lastupdate'),
'%Y-%m-%d %H:%M:%S')
if 'start_process' in data and isinstance(data.get('start_process'),
basestring):
data['start_process'] = datetime.strptime(data.get('start_process'),
'%Y-%m-%d %H:%M:%S')
get = mongodb[collection].find_one({'slug': slug})
if get:
mongodb[collection].update({'slug': slug}, data)
return json.dumps(data, default=parse_dumps)
return {'status': 'error',
'message': 'Object not exist, please send POST to create!'}
示例11: _olt_version
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def _olt_version(self):
# Version
# 0 Unknown
# 1 V1 OMCI format
# 2 V2 OMCI format
# 3 2018-01-11 or later
version = 0
info = self._rest_support.get('module-info', [dict()])
hw_mod_ver_str = next((mod.get('revision') for mod in info
if mod.get('module-name', '').lower() == 'gpon-olt-hw'), None)
if hw_mod_ver_str is not None:
try:
from datetime import datetime
hw_mod_dt = datetime.strptime(hw_mod_ver_str, '%Y-%m-%d')
version = 2 if hw_mod_dt >= datetime(2017, 9, 21) else 2
except Exception as e:
self.log.exception('ver-str-check', e=e)
return version
示例12: str_to_datetime_processor_factory
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def str_to_datetime_processor_factory(regexp, type_):
rmatch = regexp.match
# Even on python2.6 datetime.strptime is both slower than this code
# and it does not support microseconds.
has_named_groups = bool(regexp.groupindex)
def process(value):
if value is None:
return None
else:
try:
m = rmatch(value)
except TypeError:
raise ValueError("Couldn't parse %s string '%r' "
"- value is not a string." %
(type_.__name__, value))
if m is None:
raise ValueError("Couldn't parse %s string: "
"'%s'" % (type_.__name__, value))
if has_named_groups:
groups = m.groupdict(0)
return type_(**dict(list(zip(
iter(groups.keys()),
list(map(int, iter(groups.values())))
))))
else:
return type_(*list(map(int, m.groups(0))))
return process
示例13: get_newest
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def get_newest(base_url, url_pattern, links):
'''
Returns a tuple with the newest url in the `links` list matching the
pattern `url_pattern` and a datetime object representing the creation
date of the url.
The creation date is extracted from the url using datetime.strptime().
'''
logger = logging.getLogger('auditor.srmdumps')
times = []
pattern_components = url_pattern.split('/')
date_pattern = '{0}/{1}'.format(base_url, pattern_components[0])
if len(pattern_components) > 1:
postfix = '/' + '/'.join(pattern_components[1:])
else:
postfix = ''
for link in links:
try:
time = datetime.datetime.strptime(link, date_pattern)
except ValueError:
pass
else:
times.append((str(link) + postfix, time))
if not times:
msg = 'No links found matching the pattern {0} in {1}'.format(date_pattern, links)
logger.error(msg)
raise Exception(msg)
return max(times, key=operator.itemgetter(1))
示例14: get_dt_header
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def get_dt_header(self, header_key):
"""
A helper method to retrieve a response header as a date+time.
Args/kwargs:
`header_key`:
The name of the HTTP response header.
Returns:
`None` or UTC date+time as a `datetime.datetime` instance
(a naive one, i.e., without explicit timezone information).
Example usage:
with RequestPerformer('GET', 'http://example.com/FOO') as perf:
foo_last_modified = perf.get_dt_header('Last-Modified')
if foo_last_modified is None:
print 'I have no idea when FOO was modified.`
else:
print 'FOO modification date+time:', foo_last_modified.isoformat()
"""
raw_value = (self.response.headers.get(header_key) or '').strip()
if raw_value:
for dt_format in self._HTTP_DATETIME_FORMATS:
try:
return datetime.datetime.strptime(raw_value, dt_format)
except ValueError:
pass
try:
return parse_iso_datetime_to_utc(raw_value)
except ValueError:
pass
return None
示例15: _try_to_set_http_last_modified
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import strptime [as 别名]
def _try_to_set_http_last_modified(self, headers):
http_header = headers.get(self._http_last_modified_header)
if http_header:
for dt_format in self._http_datetime_formats:
try:
parsed_datetime = datetime.datetime.strptime(http_header, dt_format)
except ValueError:
pass
else:
self._http_last_modified = parsed_datetime
break