def watime(inp, bot=None):
"""time <area> -- Gets the time in <area>"""
query = "current time in {}".format(inp)
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
if not api_key:
return "error: no wolfram alpha api key set"
request = http.get_xml(api_url, input=query, appid=api_key)
time = " ".join(request.xpath("//pod[@title='Result']/subpod/plaintext/text()"))
time = time.replace(" | ", ", ")
if time:
# nice place name for UNIX time
if inp.lower() == "unix":
place = "Unix Epoch"
else:
place = capitalize_first(" ".join(request.xpath("//pod[@"
"title='Input interpretation']/subpod/plaintext/text()"))[
16:])
return "{} - \x02{}\x02".format(time, place)
else:
return u"Could not get the time for '{}'.".format(inp)
python类replace()的实例源码
def UpateEvent(self, after_values, befor_values):
_set = []
_where = []
if self._is_pri:
_where.append(self.__join(self._is_pri[0][0], after_values[self._is_pri[0][1]]))
else:
for i, column in enumerate(self.column_list):
_where.append(self.__join(column[0], after_values[i]))
for i, column in enumerate(self.column_list):
_set.append(self.__join(column[0], befor_values[i]))
sql = 'update {}.{} set {} where {}'.format(_rollback.database, _rollback.table,
','.join(_set).replace(" ", ""), ','.join(_where))
if _remote_filed._rollback_status:
print '{: >21}{}{}'.format('', '-- ', sql)
else:
self.__tmppack(sql, 2)
def UpateEvent(self,after_values,befor_values):
_set = []
_where = []
if self._is_pri:
_where.append(self.__join(self._is_pri[0][0],after_values[self._is_pri[0][1]]))
else:
for i,column in enumerate(self.column_list):
_where.append(self.__join(column[0],after_values[i]))
for i,column in enumerate(self.column_list):
_set.append(self.__join(column[0],befor_values[i]))
sql = 'update {}.{} set {} where {}'.format(_rollback.database, _rollback.table, ','.join(_set).replace(" ",""), ','.join(_where))
if _remote_filed._rollback_status:
print '{: >21}{}{}'.format('', '-- ',sql)
else:
self.__tmppack(sql, 2)
def get_latest_fragments(zoomlv=zoom_level):
res = safe_urlopen(latest_json_url)
jsonstr = res.read() # like this: {"date":"2017-02-27 01:20:00","file":"PI_H08_20170227_0120_TRC_FLDK_R10_PGPFD.png"}
try:
datadict = json.loads(jsonstr)
except Exception as e:
print "ERROR:\nbad response, maybe you are behind of firewall.\nplease test you network and retry."
raw_input("anykey to quit")
sys.exit(1)
datestr = datadict.get("date", "")
if datestr == "":
print "bad date string"
sys.exit(1)
date, time = datestr.split(" ")#"2017-02-27 22:20:00".split(" ")#
date, time = date.replace("-", "/"), time.replace(":", "")
return get_fragments_by_date(date, time, zoomlv)
def format(self, value, property, context):
if isinstance(value, datetime.datetime):
if value.tzinfo:
# DST ? ???? ???.
value = value.replace(tzinfo=timezone.utc) - value.utcoffset()
return int(calendar.timegm(value.timetuple())) + (value.microsecond / 1000000.0)
elif isinstance(value, datetime.time):
seconds = value.hour * 3600 + value.minute * 60 + value.second
if value.tzinfo:
# DST ? ???? ???.
seconds -= value.utcoffset().total_seconds()
return seconds % 86400 + (value.microsecond / 1000000.0)
elif isinstance(value, datetime.date):
return calendar.timegm(value.timetuple())
else:
raise ValueError()
def historical_price(request):
fiat = request.GET['fiat'].upper()
crypto = request.GET['currency'].upper()
try:
time = arrow.get(request.GET['time']).datetime
except:
return http.JsonResponse({'error': "Invalid Time argument"}, status=400)
try:
price = PriceTick.nearest(crypto, fiat, time)
except PriceTick.DoesNotExist:
return http.JsonResponse(
{'error': "Can't get historical price for %s->%s" % (fiat, crypto)},
status=400
)
try:
naive_time = time.replace(tzinfo=None)
price['estimated_supply'] = SupplyEstimator(crypto).calculate_supply(at_time=naive_time)
except NotImplementedError:
pass
price['currency'] = crypto
return http.JsonResponse(price)
def timefunction(inp, nick="", reply=None, db=None, notice=None):
"time [location] [dontsave] | [@ nick] -- Gets time for <location>."
save = True
if '@' in inp:
nick = inp.split('@')[1].strip()
location = database.get(db,'users','location','nick',nick)
if not location: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
else:
location = database.get(db,'users','location','nick',nick)
if not inp:
if not location:
notice(time.__doc__)
return
else:
# if not location: save = True
if " dontsave" in inp: save = False
location = inp.split()[0]
# now, to get the actual time
try:
url = "https://www.google.co.uk/search?q=time+in+{}".format(location.replace(' ','+').replace(' save',''))
request = urllib2.Request(url, None, headers)
page = urllib2.urlopen(request).read()
soup = BeautifulSoup(page, 'lxml')
soup = soup.find('div', attrs={'id': re.compile('ires')})
time = filter(None, http.strip_html(soup.find('div', attrs={'class': re.compile('vk_gy')}).renderContents().strip()).split(' '))
prefix = ' '.join(time[6:])
curtime = time[0]
day = time[1]
date = ' '.join(time[2:4])
except IndexError:
return "Could not get time for that location."
if location and save: database.set(db,'users','location',location,'nick',nick)
return formatting.output('Time', [u'{} is \x02{}\x02 [{} {}]'.format(prefix, curtime, day, date)])
def timefunction2(inp, nick="", reply=None, db=None, notice=None):
"time [location] [dontsave] | [@ nick] -- Gets time for <location>."
save = True
if '@' in inp:
nick = inp.split('@')[1].strip()
location = database.get(db,'users','location','nick',nick)
if not location: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
else:
location = database.get(db,'users','location','nick',nick)
if not inp:
if not location:
notice(time.__doc__)
return
else:
# if not location: save = True
if " dontsave" in inp: save = False
location = inp.split()[0]
url = "https://time.is/%s" % location.replace(' ','+').replace(' save','')
html = http.get_html(url)
prefix = html.xpath("//div[@id='msgdiv']/h1/a/text()")[0].strip()
curtime = html.xpath("//div[contains(@id,'twd')]/text()")[0].strip()
ampm = html.xpath("//div[contains(@id,'twd')]/span/text()")[0].strip()
date = html.xpath("//h2[contains(@id,'dd')]/text()")[0].strip()
# now, to get the actual time
try:
url = "https://time.is/%s" % location.replace(' ','+').replace(' save','')
html = http.get_html(url)
prefix = html.xpath("//div[@id='msgdiv']/h1/a/text()")[0].strip()
curtime = html.xpath("//div[contains(@id,'twd')]/text()")[0].strip()
ampm = html.xpath("//div[contains(@id,'twd')]/span/text()")[0].strip()
date = html.xpath("//h2[contains(@id,'dd')]/text()")[0].strip()
except IndexError:
return "Could not get time for that location."
if location and save: database.set(db,'users','location',location,'nick',nick)
print(prefix, curtime, ampm, date)
return u'Time in {} is \x02{} {}\x02 [{}]'.format(prefix, curtime, ampm.upper(), date)
def getUnstructuredTime (log, patern, dateFormat):
# Fuction to extrat timestamp from an unstructured source
p = re.search(patern,log)
try:
date_string = p.group(0)
d = datetime.strptime(date_string,dateFormat)
d = d.replace(second = 00)
return d.strftime(dateFormat)
except:
return None
def getStructuredTime(line, pos, dateFormat):
valueList = line.split(',')
rawTime = valueList[pos].split('.')[0]
time = datetime.strptime(rawTime, dateFormat)
time = time.replace(second = 00)
return time
def __add_fsp_to_time(self, time, column):
"""Read and add the fractional part of time
For more details about new date format:
"""
microsecond, read = self.__read_fsp(column)
if microsecond > 0:
time = time.replace(microsecond=microsecond)
return time, read
def __add_fsp_to_time(self, time, column):
"""Read and add the fractional part of time
For more details about new date format:
"""
microsecond,read = self.__read_fsp(column)
if microsecond > 0:
time = time.replace(microsecond=microsecond)
return time,read
def parse(self, value, property, context):
if not isinstance(value, (integer_types, float)):
raise ValueError()
decoded = datetime.datetime.utcfromtimestamp(value)
if issubclass(property, Time):
return decoded.time().replace(tzinfo=timezone.utc)
elif issubclass(property, Date):
return decoded.date()
return decoded.replace(tzinfo=timezone.utc)
def format(self, value, property, context):
if isinstance(value, (datetime.datetime, datetime.time)):
if value.tzinfo and value.utcoffset() == datetime.timedelta():
return value.replace(tzinfo=None).isoformat() + 'Z'
return value.isoformat()
elif isinstance(value, datetime.date):
return value.isoformat()
else:
raise ValueError()
def _format(self, value, property, context, gmt):
if isinstance(value, datetime.time):
value = datetime.datetime.combine(datetime.date.fromtimestamp(0), value)
elif not isinstance(value, datetime.datetime):
value = datetime.datetime.combine(value, datetime.time())
if gmt:
if value.tzinfo and value.utcoffset() != datetime.timedelta():
value = value.replace(tzinfo=timezone.utc) - value.utcoffset()
format = '%s, %%d %s %%Y %%H:%%M:%%S GMT'
else:
TZ = (' %%z' if value.utcoffset() != datetime.timedelta() else ' GMT') if value.tzinfo else ''
format = '%s, %%d %s %%Y %%H:%%M:%%S' + TZ
format = format % (self.WDAY[value.weekday()], self.MON[value.month - 1])
return value.strftime(format)
def saylua_time(time):
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
time = time.replace(tzinfo=from_zone)
return time.astimezone(to_zone)
def saylua_time(time):
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
time = time.replace(tzinfo=from_zone)
return time.astimezone(to_zone)
def log():
import logging
logger = logging.getLogger(__name__)
print logger.name
# log()
# from scrapy.selector import Selector
# import requests
# url = 'http://cuiqingcai.com/2621.html'
# body = requests.get(url).content
# s = Selector(text=body)
# se = s.xpath("//h1[@class='article-title']/a")
# for i in se:
# print i.xpath("./@href").extract_first()
# print i.xpath("./text()").extract()
# s = ["\n\n\n\rddfd\n\r\n\ndfdf", '\n\n\ndfdfd', 'fdf']
# print ''.join(s).replace("\n", '')
# from scrapy.selector import Selector
# body = Selector(text=body)
# body.xpath("").extract_first()
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# import requests
#
# from scrapy import Selector
#
# url = 'https://book.douban.com/top250'
# respones = requests.get(url=url).content
# selector = Selector(text=respones)
# infos = selector.xpath('//tr[@class="item"]')
# for info in infos:
# bookname = info.xpath('td/div/a/@title').extract_first()
# url = info.xpath('td/div/a/@href').extract_first()
# author_info = info.xpath('td/p/text()').extract_first()
# print(bookname)
# print(url)
# print(author_info)
def getMAC(separeate = None, capitalization=False):
mac = hex(uuid.getnode()).replace('0x', '')
if capitalization is not False:
mac = mac.upper()
return "".join(mac[i:i+2] for i in range(0, 11, 2)) if separeate is None \
else separeate.join(mac[i:i+2] for i in range(0, 11, 2))
def reformatDateTimeString(dateString, timeString = None):
def normaliseDate(date):
return date.replace(".", "-").replace("_", "-")
def normaliseTime(time):
return time.replace(".", ":").replace("-", ":")
if dateString.find("_") >= 0: # Format "2012-11-12_12:13:14"
dVal = dateString.split("_")
return normaliseDate(dVal[0]), normaliseTime(dVal[1])
else:
if timeString is not None:
return normaliseDate(dateString), normaliseTime(timeString)
else:
return normaliseDate(dateString), ""
def parse(self, value, property, context):
value = value.strip()
m = self.PATTERN1.match(value)
if m is None:
if issubclass(property, Time):
m = self.PATTERN2.match(value)
if m is None:
raise ValueError()
else:
raise ValueError()
if m.groupdict().get('Y'):
date = datetime.date(*map(lambda x: 1 if x is None else int(x), m.group('Y', 'm', 'd')))
else:
date = datetime.date.fromtimestamp(0)
if issubclass(property, Date):
return date
if m.group('H'):
hour, min, sec = m.group('H', 'M', 'S')
hour = int(hour)
min = int(min) if min else 0
sec = float(sec) if sec else 0.0
time = datetime.time(hour, min, int(sec), int((sec % 1.0) * 1000000))
else:
time = datetime.time()
if m.group('tzd'):
if m.group('tzd') in ('Z', '+00:00', '-00:00'):
tzinfo = timezone.utc
else:
offset = int(m.group('tzh')) * 60 + int(m.group('tzm'))
if m.group('tzd').startswith('-'):
offset = -offset
tzinfo = timezone(datetime.timedelta(minutes=offset))
time = time.replace(tzinfo=tzinfo)
if issubclass(property, Time):
return time
return datetime.datetime.combine(date, time)