本文整理汇总了Python中xbmc.getRegion函数的典型用法代码示例。如果您正苦于以下问题:Python getRegion函数的具体用法?Python getRegion怎么用?Python getRegion使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getRegion函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Hehestreams
def Hehestreams(home, away, orig_title):
try:
html = GetURL("http://hehestreams.xyz/")
titles = common.parseDOM(html, "a", attrs={"class": "results-link"})
links = common.parseDOM(html, "a", attrs={"class": "results-link"}, ret="href")
for title in titles:
if home.lower() in title.lower() and away.lower() in title.lower():
link = links[titles.index(title)]
link = "http://hehestreams.xyz"+link
html = GetURL(link)
lnks = common.parseDOM(html, "option", ret="value")
print lnks
for lnk in lnks:
if 'turner' in lnk:
try:
timest = lnk.split("exp=")[-1].split("~acl")[0]
time_exp = datetime.fromtimestamp(int(timest)).strftime(xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
except:
time_exp = ''
addDirectLink('Turner - (external player) link expires '+time_exp, {'Title': orig_title}, lnk)
elif 'neulion' in lnk:
lnk = lnk.replace('amp;','')
try:
timest = lnk.split("expires%3D")[-1].split("%7E")[0]
time_exp = datetime.fromtimestamp(int(timest)).strftime(xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
except:
time_exp = ''
addDirectLink('Neulion link expires '+time_exp, {'Title': orig_title}, lnk)
except:
pass
示例2: _normalize_outlook
def _normalize_outlook( self, outlook ):
# set temperature and speed unit
tempunit = xbmc.getRegion( id="tempunit" )
speedunit = xbmc.getRegion( id="speedunit" )
# enumerate thru and localize values
for count, tmp_outlook in enumerate( outlook ):
if ( tempunit != "°F" ):
# find all temps
temps = re.findall( "[0-9]+F", tmp_outlook )
for temp in temps:
tmp_outlook = re.sub( temp, self.localize_unit( temp ) + tempunit, tmp_outlook, 1 )
# calculate the localized temp ranges if C is required
temps = re.findall( "[low|mid|high]+ [0-9]+s", tmp_outlook )
add = { "l": 3, "m": 6, "h": 9 }
for temp in temps:
new_temp = self.localize_unit( str( int( re.search( "[0-9]+", temp ).group( 1 ) ) + add.get( temp[ 0 ], 3 ) ) )
temp_int = int( float( new_temp ) / 10 ) * 10
temp_rem = int( float( new_temp ) % 10 )
temp_text = [ "low %ds", "mid %ds", "high %ds" ][ ( temp_rem >= 4 ) + ( temp_rem >= 6 ) ]
tmp_outlook = re.sub( temp, temp_text % ( temp_int, ), tmp_outlook, 1 )
if ( speedunit != "mph" ):
# calculate the localized wind if C is required
winds = re.findall( "[0-9]+ to [0-9]+ mph", tmp_outlook )
for wind in winds:
speeds = re.findall( "[0-9]+", wind )
for speed in speeds:
wind = re.sub( speed, self.localize_unit( speed, "speed" ).split( " " )[ 0 ], wind, 1 )
tmp_outlook = re.sub( "[0-9]+ to [0-9]+ mph", wind.replace( "mph", speedunit ), tmp_outlook, 1 )
# add our text back to the main variable
outlook[ count ] = tmp_outlook
# return normalized text
return outlook
示例3: format_date_new
def format_date_new(date, abbrev=False, time=False, pretty=True, if_modified=False, hours=0):
#def format_date(date, pretty=True, short=True, reverse=False, modified=False, hours=0):
try: #FIXME: clean this up, too many hacks
# set proper format
# Thursday, March 7, 2013 - Thu, Mar 7, 2013
pretty_output = [xbmc.getRegion("datelong"), xbmc.getRegion("datelong").replace("%A", "%a").replace("%B", "%b")][abbrev]
# 03/07/2013 02:30:00 pm - 03/07/2013
regular_output = ["{date} {hours}".format(date=xbmc.getRegion("dateShort"), time=xbmc.getRegion("dateShort")), xbmc.getRegion("dateShort")][short]
# Thu, 13 Mar 2013 14:30:00 GMT
if_modified_output = "%a, %d %b %Y %H:%M:%S GMT"
format = [
[["%Y-%m-%d %H:%M:%S", "%Y-%m-%d"][short], [xbmc.getRegion("dateshort"), xbmc.getRegion("datelong")][pretty]],
["%Y-%m-%d %H:%M:%S", "%a, %d %b %Y %H:%M:%S GMT"]
][modified]
"""
['xbmc.getRegion("dateshort")', '%m/%d/%Y']
['xbmc.getRegion("datelong")', '%A, %B %d, %Y']
format = {
"input": ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d"][short],
"output": [xbmc.getRegion("dateshort"), "%a, %d %b %Y %H:%M:%S GMT"][if_modified]
}
"long": {
"input": ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"][if_modified],
"output": [xbmc.getRegion("dateshort"), "%a, %d %b %Y %H:%M:%S GMT"][if_modified]
}
[xbmc.getRegion("dateshort"), xbmc.getRegion("datelong")][pretty]
],
["%Y-%m-%d %H:%M:%S", "%a, %d %b %Y %H:%M:%S GMT"]
][if_modified]
"""
# reverse for saving in NFO and DB
if (reverse):
format.reverse()
# format as date/time
if (modified):
dt = datetime.datetime(*time.strptime(date, format[0])[ : 6]) + datetime.timedelta(hours=hours)
# format as date
else:
dt = datetime.date(*time.strptime(date, format[0])[ : 3])
# return result
#print format
return dt.strftime(format[1])
except Exception as error:
#print str(error)
# something is wrong, return original
return date
示例4: getDateFormat
def getDateFormat():
df = xbmc.getRegion("dateshort")
tf = xbmc.getRegion("time").split(":")
try:
# time format is 12h with am/pm
return df + " " + tf[0][0:2] + ":" + tf[1] + " " + tf[2].split()[1]
except IndexError:
# time format is 24h with or w/o leading zero
return df + " " + tf[0][0:2] + ":" + tf[1]
示例5: _get_local_date
def _get_local_date(self, datestr, long_date=False):
'''returns the localized representation of the date provided by the api'''
result = ""
try:
if long_date:
result = arrow.get(datestr).strftime(xbmc.getRegion('datelong'))
else:
result = arrow.get(datestr).strftime(xbmc.getRegion('dateshort'))
except Exception as exc:
self._log_msg("Exception in _get_local_date: %s" % exc)
return result
示例6: Games
def Games(mode):
GAMEURL = 'https://www.reddit.com/r/'+mode+'streams'
today = datetime.utcnow() - timedelta(hours=8)
today_from = str(today.strftime('%Y-%m-%d'))+'T00:00:00.000-05:00'
today_to = str(today.strftime('%Y-%m-%d'))+'T23:59:00.000-05:00'
js = GetJSON('http://www.sbnation.com/sbn_scoreboard/ajax_leagues_and_events?ranges['+mode+'][from]='+today_from+'&ranges['+mode+'][until]='+today_to)
js = js['leagues'][mode]
if js:
if mode == 'nfl':
addDir('[COLOR=FF00FF00][B]NFL Redzone[/B][/COLOR]', GAMEURL, iconImg=logos[mode], home='redzone', away='redzone', mode="STREAMS")
for game in js:
home = game['away_team']['name']
away = game['home_team']['name']
hs = str(game['score']['home'][game['score']['cols'].index('Total')])
if not hs:
hs = '0'
avs = str(game['score']['away'][game['score']['cols'].index('Total')])
if not avs:
avs = '0'
score = ' - '+avs+':'+hs
start_time = game['start_time']
try:
plus = False
st = start_time.replace('T', ' ')
if '+' in st:
plus = True
str_new = st.split('+')[-1]
st = st.replace('+'+str_new,'')
else:
str_new = st.split('-')[-1]
st = st.replace('-'+str_new,'')
str_new = str_new.split(':')[0]
if plus:
st_time_utc = datetime(*(time.strptime(st, '%Y-%m-%d %H:%M:%S')[0:6]))-timedelta(hours=int(str_new))
else:
st_time_utc = datetime(*(time.strptime(st, '%Y-%m-%d %H:%M:%S')[0:6]))+timedelta(hours=int(str_new))
local_game_time = utc_to_local(st_time_utc)
local_time_str = ' - '+local_game_time.strftime(xbmc.getRegion('dateshort')+' '+xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
except:
local_time_str = ''
status = GameStatus(game['status'])
status = ' - '+status
title = '[COLOR=FF00FF00][B]'+game['title'].replace(game['title'].split()[-1],'')+'[/B][/COLOR]'
if display_start_time=='true':
title = title+'[COLOR=FFFFFF00]'+local_time_str+'[/COLOR]'
if display_status=='true':
title = title+'[COLOR=FFFF0000]'+status+'[/COLOR]'
if display_score=='true':
title = title+'[COLOR=FF00FFFF]'+score+'[/COLOR]'
addDir(title, GAMEURL, iconImg=logos[mode], home=home, away=away, mode="STREAMS")
else:
addDir("[COLOR=FFFF0000]Could not fetch today's "+mode.upper()+" games... Probably no games today?[/COLOR]", '', iconImg="", mode="")
xbmcplugin.endOfDirectory(h, cacheToDisc=True)
示例7: getSettings
def getSettings(self):
self.__showNoticeBeforeSw = True if __addon__.getSetting('showNoticeBeforeSw').upper() == 'TRUE' else False
self.__dispMsgTime = int(re.match('\d+', __addon__.getSetting('dispTime')).group())*1000
self.__discardTmr = int(re.match('\d+', __addon__.getSetting('discardOldTmr')).group())*60
self.__confirmTmrAdded = True if __addon__.getSetting('confirmTmrAdded').upper() == 'TRUE' else False
df = xbmc.getRegion('dateshort')
tf = xbmc.getRegion('time').split(':')
self.__dateFormat = df + ' ' + tf[0][0:2] + ':' + tf[1]
notifyLog('settings (re)loaded')
self.SettingsChanged = False
示例8: _get_local_time
def _get_local_time(self, timestr):
'''returns the correct localized representation of the time provided by the api'''
result = ""
try:
if timestr and ":" in timestr:
timestr = timestr.replace(".", ":")
if "H" in xbmc.getRegion('time'):
time_format = "HH:mm"
else:
time_format = "h:mm A"
if " AM" in timestr or " PM" in timestr:
result = arrow.get(timestr, 'h:mm A').format(time_format, locale=KODI_LANGUAGE)
elif " am" in timestr or " pm" in timestr:
result = arrow.get(timestr, 'h:mm a').format(time_format, locale=KODI_LANGUAGE)
elif "AM" in timestr or "PM" in timestr:
result = arrow.get(timestr, 'h:mmA').format(time_format, locale=KODI_LANGUAGE)
elif "am" in timestr or "pm" in timestr:
result = arrow.get(timestr, 'h:mma').format(time_format, locale=KODI_LANGUAGE)
elif len(timestr.split(":")[0]) == 1:
result = arrow.get(timestr, 'h:mm').format(time_format, locale=KODI_LANGUAGE)
else:
result = arrow.get(timestr, 'HH:mm').format(time_format, locale=KODI_LANGUAGE)
except Exception as exc:
self._log_msg(str(exc), xbmc.LOGWARNING)
return timestr
return result
示例9: round_down_to_half_hour
def round_down_to_half_hour(xtime):
"""
Returns a string with the time rounded down to the nearest half-hour in format h:mm am
Example:
now_time = time.localtime()
r_time = round_down_to_half_hour(now_time)
> 7:30 am
@param xtime: the time to be converted in either string YYYYmmddHHMMSS format or a time.struct_time typed obj
@type xtime: str
@type xtime: time.struct_time
@rtype: str
"""
if type(xtime) is str:
try:
xxtime = time.strptime(xtime, '%Y%m%d%H%M%S')
except:
return None
elif type(xtime) is time.struct_time:
xxtime = xtime
else:
return None
if xxtime.tm_min <= 30:
newmin = ':00'
else:
newmin = ':30'
xformat = xbmc.getRegion('time').replace(':%S', '').replace('%H%H', '%H')
tmp = time.strftime(xformat, xxtime).lower()
ret = re.sub(':..', newmin, tmp)
return ret
示例10: format_time
def format_time(self, time_obj):
time_format = xbmc.getRegion('time')
_time_obj = time_obj
if isinstance(_time_obj, datetime.time):
_time_obj = datetime.time(_time_obj.hour, _time_obj.minute, _time_obj.second)
return _time_obj.strftime(time_format.replace("%H%H", "%H"))
示例11: format_date_short
def format_date_short(self, date_obj):
date_format = xbmc.getRegion('dateshort')
_date_obj = date_obj
if isinstance(_date_obj, datetime.date):
_date_obj = datetime.datetime(_date_obj.year, _date_obj.month, _date_obj.day)
return _date_obj.strftime(date_format)
示例12: _fetch_changelog
def _fetch_changelog(self, view, msg):
def _pysvn_cancel_callback():
# check if user cancelled operation
return False
# import required modules
import datetime
import pysvn
# get our regions format
date_format = "{date} {time}".format(date=xbmc.getRegion("datelong"), time=xbmc.getRegion("time"))
# get client
client = pysvn.Client()
client.callback_cancel = _pysvn_cancel_callback
try:
# grab current revision and repo URL
info = client.info(path=self.m_addon.getAddonInfo("Path"))
# fetch changelog for current revision
if (view == "changelog"):
log = client.log(url_or_path=info["url"], limit=25, revision_start=pysvn.Revision(pysvn.opt_revision_kind.number, info["commit_revision"].number))
# updates
else:
log = client.log(url_or_path=info["url"], limit=25, revision_end=pysvn.Revision(pysvn.opt_revision_kind.number, info["commit_revision"].number + 1))
except:
# changelog
log = client.log(url_or_path=u"{repo}{branch}{id}".format(repo=self.m_addon.getSetting("Repo"), branch=self.m_addon.getSetting("Branch"), id=self.m_addon.getAddonInfo("Id"),), limit=25)
# if no entries set user message
if (len(log)):
# initialize our log text
changelog = "{0:-<150}\n".format("")
else:
# should only happen for "updates" and there are none
changelog = self.m_addon.getLocalizedString(30701)
# we need to compile so we can add flags
clean_entry = re.compile("\[.+?\][\s]+(?P<name>[^\[]+)(?:\[.+)?", re.DOTALL)
version = re.compile("(Version.+)", re.IGNORECASE)
# iterate thru and format each message
for entry in log:
# add version
changelog += u"{version}\n".format(version=version.search(entry["message"]).group(1))
# add heading
changelog += u"r{revision} - {date} - {author}\n".format(revision=entry["revision"].number, date=datetime.datetime.fromtimestamp(entry["date"]).strftime(date_format), author=entry["author"])
# add formatted message
changelog += "\n".join([re.sub("(?P<name>^[a-zA-Z])", "- \\1", line.lstrip(" -")) for line in entry["message"].strip().splitlines() if (not line.startswith("["))])
# add separator
changelog += "\n{0:-<150}\n".format("")
return self._colorize_text(changelog)
示例13: format_time
def format_time(self, time_obj):
time_format = xbmc.getRegion("time")
_time_obj = time_obj
if isinstance(_time_obj, datetime.time):
_time_obj = datetime.time(_time_obj.hour, _time_obj.minute, _time_obj.second)
pass
return _time_obj.strftime(time_format)
示例14: __init__
def __init__( self, xmlSource, settings, MediaWindow ):
self.success = True
self.settings = settings
self.MediaWindow = MediaWindow
# get our regions format
self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
# get the list
self.success = self._get_current_videos( xmlSource )
示例15: LIST_STREAMS
def LIST_STREAMS():
live_streams = []
upcoming_streams = []
url = 'http://api.new.livestream.com/curated_events?page=1&maxItems=500'
req = urllib2.Request(url)
req.add_header('User-Agent', IPHONE_UA)
response = urllib2.urlopen(req)
json_source = json.load(response)
response.close()
for event in json_source['data']:
event_id = str(event['id'])
owner_id = str(event['owner_account_id'])
owner_name = name = event['owner']['full_name'].encode('utf-8')
full_name = event['full_name'].encode('utf-8')
name = owner_name + ' - ' + full_name
icon = event['logo']['url']
#2013-03-26T14:28:00.000Z
pattern = "%Y-%m-%dT%H:%M:%S.000Z"
start_time = str(event['start_time'])
end_time = str(event['end_time'])
current_time = datetime.utcnow().strftime(pattern)
my_time = int(time.mktime(time.strptime(current_time, pattern)))
event_end = int(time.mktime(time.strptime(end_time, pattern)))
length = 0
try:
length = int(item['duration'])
except:
pass
print start_time
aired = start_time[0:4]+'-'+start_time[5:7]+'-'+start_time[8:10]
print aired
info = {'plot':'','tvshowtitle':'Livestream','title':name,'originaltitle':name,'duration':length,'aired':aired}
if event['in_progress']:
name = '[COLOR=FF00B7EB]'+name+'[/COLOR]'
live_streams.append([name,icon,event_id,owner_id,info])
else:
if my_time < event_end:
start_date = datetime.fromtimestamp(time.mktime(time.strptime(start_time, pattern)))
start_date = datetime.strftime(utc_to_local(start_date),xbmc.getRegion('dateshort')+' '+xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
info['plot'] = "Starting at: "+str(start_date)
#name = name + ' ' + start_date
upcoming_streams.append([name,icon,event_id,owner_id,info])
for stream in sorted(live_streams, key=lambda tup: tup[0]):
addDir(stream[0],'/live_now',101,stream[1],FANART,stream[2],stream[3],stream[4])
for stream in sorted(upcoming_streams, key=lambda tup: tup[0]):
addDir(stream[0],'/live_now',101,stream[1],FANART,stream[2],stream[3],stream[4])