def validate_year( value ): # {{{1
""" it validates ``value.year`` newer than 1900 and less than 2 years from
now.
``date`` and ``datetime`` have this property.
Event dates which are more than two years in the future are very likely to
be a human mistake entering the data.
This validator is needed because some functions like datetime.strftime()
raise a ValueError when the year is older than 1900. See the discussion at
http://bugs.python.org/issue1777412
"""
if value.year <= 1900:
raise ValidationError(
_( u'%(year)s is before 1900, which is not allowed' ) % \
{'year': value.year,} )
if value > datetime.date.today() + relativedelta( years = 4 ):
raise ValidationError(
_( u'%(year)s is more than four years in the future, ' \
'which is not allowed' ) % {'year': value.year,} )
python类strftime()的实例源码
def updated_releases(self, since):
'''Fetch all releases younger than "since" argument.
'''
assert isinstance(since, int)
cursor = self.get_cursor()
safe_execute(cursor, '''
select j.name,j.version,j.submitted_date,r.summary
from journals j, releases r
where j.version is not NULL
and j.action = 'new release'
and j.name = r.name and j.version = r.version
and r._pypi_hidden = '''+self.false+'''
and j.submitted_date > %s
order by submitted_date desc
''', (time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime(since)),))
return Result(None, self.get_unique(cursor.fetchall()),
self._Updated_Releases)
def changelog(self, since, full=False):
'''Fetch (name, version, submitted_date, action, id) since 'since'
argument.
'''
assert isinstance(since, int)
cursor = self.get_cursor()
query = '''
select name, version, submitted_date, action, id
from journals j
where j.submitted_date > %s
order by j.submitted_date
'''
if not full:
query += 'limit 50000'
params = (time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime(since)),)
safe_execute(cursor, query, params)
return Result(None, cursor.fetchall(), self._Changelog)
def remove_file(self, digest):
cursor = self.get_cursor()
sql = '''select python_version, name, version, filename, has_signature,
path
from release_files
where md5_digest=%s'''
safe_execute(cursor, sql, (digest, ))
info = cursor.fetchone()
if not info:
raise KeyError, 'no such file'
pyversion, name, version, filename, has_sig, filepath = info
safe_execute(cursor, 'delete from release_files where md5_digest=%s',
(digest, ))
self._deleted_files.add(filepath)
if has_sig:
self._deleted_files.add(filepath + ".asc")
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
self.add_journal_entry(name, version, "remove file %s" % filename,
date, self.username, self.userip)
self._add_invalidation(name)
def isotime(at=None, subsecond=False):
"""Stringify time in ISO 8601 format.
.. deprecated:: 1.5.0
Use :func:`utcnow` and :func:`datetime.datetime.isoformat` instead.
"""
if not at:
at = utcnow()
st = at.strftime(_ISO8601_TIME_FORMAT
if not subsecond
else _ISO8601_TIME_FORMAT_SUBSECOND)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
"""Returns formatted utcnow.
.. deprecated:: 1.5.0
Use :func:`utcnow()`, :func:`datetime.datetime.isoformat`
or :func:`datetime.strftime` instead:
* ``strtime()`` => ``utcnow().isoformat()``
* ``strtime(fmt=...)`` => ``utcnow().strftime(fmt)``
* ``strtime(at)`` => ``at.isoformat()``
* ``strtime(at, fmt)`` => ``at.strftime(fmt)``
"""
if not at:
at = utcnow()
return at.strftime(fmt)
def get_city_yyb(self):
url = "http://data.eastmoney.com/stock/yybcx.html"
_data = self.sGet(url)
_urls = self.sMatch('href="/Stock/lhb/city/', '\.html"', _data, 0)
for x in xrange(0, len(_urls)):
#_urls[x] = 440000
detail = "http://data.eastmoney.com/DataCenter_V3/stock2016/yybSearch.ashx?pagesize=1000&page=1&js=var+fguIHta¶m=&sortRule=-1&sortType=UpCount&city=%s&typeCode=2&gpfw=0&code=%s&rt=24462162" % (_urls[x], _urls[x])
a = self.sGet(detail)
a = a.replace("var fguIHta=", "")
re = json.loads(a)
for k in range(0, len(re['data'])):
_tmp = re['data'][k]
indata = {
'province': _tmp['Province'],
'codex': _tmp['SalesCode'],
'name': _tmp['SalesName'],
'SumActMoney': _tmp['SumActMoney'],
'SumActBMoney': _tmp['SumActBMoney'],
'SumActSMoney': _tmp['SumActSMoney'],
'UpCount': _tmp['UpCount'],
'BCount': _tmp['BCount'],
'SCount': _tmp['SCount']
}
print indata
_has = self.mysql.fetch_one("select * from s_lhb where codex=%s" % _tmp['SalesCode'])
_where = "codex=%s" % _tmp['SalesCode']
if _has is not None:
self.mysql.dbUpdate('s_lhb', indata, _where)
else:
indata['last_dateline'] = datetime.strftime(date.today(), "%Y%m%d")
self.mysql.dbInsert('s_lhb', indata)
def online_time_to_string(value, timeFormat, utcOffset=0):
"""Converts AGOL timestamp to formatted string.
Args:
value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
utcOffset (int): Hours difference from UTC and desired output. Default is 0 (remain in UTC).
Returns:
str: A string representation of the timestamp.
Examples:
>>> arcresthelper.common.online_time_to_string(1457167261000.0, "%Y-%m-%d %H:%M:%S")
'2016-03-05 00:41:01'
>>> arcresthelper.common.online_time_to_string(731392515000.0, '%m/%d/%Y %H:%M:%S', -8) # PST is UTC-8:00
'03/05/1993 12:35:15'
See Also:
:py:func:`local_time_to_online` for converting a :py:class:`datetime.datetime` object to AGOL timestamp
"""
try:
return datetime.datetime.fromtimestamp(value/1000 + utcOffset*3600).strftime(timeFormat)
except:
line, filename, synerror = trace()
raise ArcRestHelperError({
"function": "online_time_to_string",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
pass
#----------------------------------------------------------------------
def online_time_to_string(value, timeFormat, utcOffset=0):
"""Converts AGOL timestamp to formatted string.
Args:
value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
utcOffset (int): Hours difference from UTC and desired output. Default is 0 (remain in UTC).
Returns:
str: A string representation of the timestamp.
Examples:
>>> rcrest.general.online_time_to_string(1457167261000.0, "%Y-%m-%d %H:%M:%S")
'2016-03-05 00:41:01'
>>> rcrest.general.online_time_to_string(731392515000.0, '%m/%d/%Y %H:%M:%S', -8) # PST is UTC-8:00
'03/05/1993 12:35:15'
See Also:
:py:func:`local_time_to_online` for converting a :py:class:`datetime.datetime` object to AGOL timestamp
"""
try:
return datetime.datetime.fromtimestamp(value/1000 + utcOffset*3600).strftime(timeFormat)
except:
return ""
finally:
pass
#----------------------------------------------------------------------
def _to_timestamp(datetime):
'''convert datetime to unix timestamp in python2 compatible manner.'''
try:
return datetime.timestamp()
except AttributeError:
return int(datetime.strftime('%s'))
def make_key(precision, datetime, key):
return "downloads:%s:%s:%s" % (
precision[0], datetime.strftime(precision[1]), key)
def changed_packages(self, since):
"Fetch list of names of packages changed 'since'"
assert isinstance(since, int)
cursor = self.get_cursor()
safe_execute(cursor, 'select distinct(name) from journals where submitted_date > %s',
(time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime(since)),))
return [r[0] for r in cursor.fetchall()]
def remove_release(self, name, version):
''' Delete a single release from the database.
'''
cursor = self.get_cursor()
self._add_invalidation(name)
# delete the files
to_delete = []
for file in self.list_files(name, version):
to_delete.append(file['path'])
self._deleted_files |= set(to_delete)
# delete ancillary table entries
for tab in ('files', 'dependencies', 'classifiers'):
safe_execute(cursor, '''delete from release_%s where
name=%%s and version=%%s'''%tab, (name, version))
safe_execute(cursor, 'delete from description_urls where name=%s and version=%s',
(name, version))
# delete releases table entry
safe_execute(cursor, 'delete from releases where name=%s and version=%s',
(name, version))
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
self.add_journal_entry(name, version, "remove", date,
self.username, self.userip)
def rename_package(self, old, new):
''' Rename a package. Relies on cascaded updates.
'''
cursor = self.get_cursor()
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
safe_execute(cursor, '''update packages set name=%s where name=%s''',
(new, old))
safe_execute(cursor, '''update journals set name=%s where name=%s''',
(new, old))
# move all files on disk
sql = '''select id, blake2_256_digest, filename, path
from release_files where name=%s'''
safe_execute(cursor, sql, (new,))
for fid, digest, filename, path in cursor.fetchall():
assert digest is not None, "Cannot Move a file without a blake2 digest"
oldname = path
newname = self.gen_file_path(digest, filename)
safe_execute(
cursor,
"update release_files set path=%s where id=%s",
(newname, fid),
)
self.package_bucket.copy_key(
os.path.join("packages", newname),
self.package_bucket.name,
os.path.join("packages", oldname),
)
self._deleted_files.add(oldname)
self.add_journal_entry(new, None, "rename from %s" % old, date,
self.username, self.userip)
self._add_invalidation(new)
self._add_invalidation(old)
self._add_invalidation(None)
def add_role(self, user_name, role_name, package_name):
''' Add a role to the user for the package.
'''
cursor = self.get_cursor()
safe_execute(cursor, '''
insert into roles (user_name, role_name, package_name)
values (%s, %s, %s)''', (user_name, role_name, package_name))
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
self.add_journal_entry(
package_name, None, "add %s %s" % (role_name, user_name), date,
self.username, self.userip)
def delete_role(self, user_name, role_name, package_name):
''' Delete a role for the user for the package.
'''
cursor = self.get_cursor()
safe_execute(cursor, '''
delete from roles where user_name=%s and role_name=%s
and package_name=%s''', (user_name, role_name, package_name))
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
self.add_journal_entry(
package_name, None, "remove %s %s" % (role_name, user_name),
date, self.username, self.userip)
def log_docs(self, name, version, operation=None):
if operation is None:
operation = 'docupdate'
cursor = self.get_cursor()
date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
self.add_journal_entry(name, version, operation, date,
self.username, self.userip)