本文整理汇总了Python中pytz.country_timezones函数的典型用法代码示例。如果您正苦于以下问题:Python country_timezones函数的具体用法?Python country_timezones怎么用?Python country_timezones使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了country_timezones函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tz_gen
def tz_gen():
yield TZ_DETECT_TIMEZONES
for c in country_hints:
yield pytz.country_timezones(c)
for c in TZ_DETECT_COUNTRIES:
yield pytz.country_timezones(c)
yield pytz.common_timezones
示例2: test3
def test3():
print pytz.country_timezones('cn')
tz_cn = pytz.timezone('Asia/Shanghai')
tz_utc = pytz.timezone('UTC')
now = time.time()
# 系统时区的时间
d = datetime.datetime.fromtimestamp(now)
# d2是一个utc时区的时间
d2 = datetime.datetime.utcfromtimestamp(now)
print d
print d2
# 将d1 d2加上自己的时区
d_cn = tz_cn.localize(d)
d_utc = tz_utc.localize(d2)
print d_cn
print d_utc
# 转换时区
d_utc2 = d_cn.astimezone(tz_utc)
print 'd_utc2', d_utc2
# 转换为unix timestamp
print calendar.timegm(d_cn.utctimetuple())
print calendar.timegm(d_utc.utctimetuple())
print calendar.timegm(d_cn.timetuple())
print calendar.timegm(d_utc.timetuple())
示例3: timezone
def timezone():
pytz.country_timezones('CN') # [u'Asia/Shanghai', u'Asia/Urumqi']
tz = pytz.timezone(u'Asia/Shanghai')
print datetime.datetime.now(tz), tz
sorted(pytz.country_timezones.keys()) # all countries' abbreviation
pytz.all_timezones # all timezone
tz = pytz.timezone(u'America/New_York')
print datetime.datetime.now(tz), tz
print datetime.datetime.now(), "Default"
# 时区错乱问题
print datetime.datetime(2016, 9, 7, 12, tzinfo=pytz.timezone(u'Asia/Shanghai')) # 平均日出时间
print datetime.datetime(2016, 9, 7, 12, tzinfo=pytz.timezone(u'Asia/Urumqi')) # 平均日出时间
print datetime.datetime(2016, 9, 7, 12, tzinfo=pytz.utc).astimezone(pytz.timezone(u'Asia/Shanghai'))
示例4: test_time_zone
def test_time_zone():
d = datetime(2016, 01, 16, 23, 18)
print d
print 'localize the date for Chicago'
central = timezone('US/Central')
loc_d = central.localize(d)
print loc_d
print 'convert to Chongqing time'
cq_d = loc_d.astimezone(timezone('Asia/Chongqing'))
print cq_d
print 'consider the one-hour daylight saving time'
cq_d2 = timezone('Asia/Chongqing').normalize(cq_d)
print cq_d2
print 'consult timezone list of China'
print country_timezones('CN')
示例5: timezones_for_country
def timezones_for_country(request, cc):
if request.method == "GET" and cc:
code = cc
countrycodes = pytz.country_timezones(code)
data = ",".join([c for c in countrycodes])
return HttpResponse(data, content_type = 'text/plain')
return
示例6: get_country_from_timezone
def get_country_from_timezone(self):
try:
import pytz
except ImportError:
print "pytz not installed"
return self.get_country_from_language()
timezone_country = {}
for country in self.country_list:
country_zones = pytz.country_timezones(country)
for zone in country_zones:
if zone not in timezone_country.iterkeys():
timezone_country[zone] = []
if country not in timezone_country[zone]:
timezone_country[zone].append(country)
if "TZ" in os.environ.keys():
timezone = os.environ.get("TZ")
else:
timezone = commands.getoutput("cat /etc/timezone")
if timezone in timezone_country.iterkeys():
if len(timezone_country[timezone]) == 1:
return timezone_country[timezone][0]
else:
return self.get_country_from_language(timezone_country[timezone])
else:
return self.get_country_from_language()
示例7: return_local_time
def return_local_time(utchour):
app.logger.info(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + '] Request: GET /localhour/' + str(utchour))
if utchour == 24:
utchour = 0
if not 0 <= utchour <= 23:
app.logger.warning(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + '] Invalid utchour ' + str(utchour))
return str('{ "error": "invalid utchour ' + str(utchour) + '" }')
# Do GeoIP based on remote IP to determine TZ
try:
match = geolite2.lookup(request.remote_addr)
except Exception as e:
app.logger.error(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + '] Error: ' + str(e) + ' - whilst matching GeoIP data for IP')
return str('{ "error": "error looking up match for IP ' + str(request.remote_addr) + '" }')
# Check we got a match
if match is None:
app.logger.error(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + "] Failed to match IP to GeoIP data")
return str('{ "error": "no geoip match for IP ' + str(request.remote_addr) + '" }')
# From the match, try pulling timezone straight from geoip lookup
try:
local = timezone(match.timezone)
except UnknownTimeZoneError:
# If we can't directly find a timezone, get one based on the Country.
local = timezone(country_timezones(match.city)[0])
#local = timezone(country_timezones(match.country)[0])
except Exception as e:
return str('{ "error": "Error: ' + str(e) + ' - whilst getting timezone" }')
app.logger.info(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + '] Matched IP to timezone: ' + str(local))
local_dt = local.localize(datetime(datetime.today().year, datetime.today().month, datetime.today().day, utchour, 0, 0))
utc_dt = utc.normalize(local_dt.astimezone(utc))
app.logger.info(str(request.remote_addr) + ' [' + str(datetime.utcnow()) + '] Returning value: ' + str(utc_dt.hour) + ' for requested hour ' + str(utchour) + ' in Timezone ' + str(local))
return str('{ "hour": ' + str(utc_dt.hour) + ' }')
示例8: main
def main():
port = "5918"
if len(sys.argv) > 1:
port = sys.argv[1]
socket = initiate_zmq(port)
logging.basicConfig(filename='./log/ingest_lottery.log', level=logging.INFO)
tz = pytz.timezone(pytz.country_timezones('cn')[0])
schedule.every(30).seconds.do(run, socket, tz)
while True:
try:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
now = datetime.now(tz)
message = "CTRL-C to quit the program at [%s]" % now.isoformat()
logging.info(message)
break
except Exception as e:
now = datetime.now(tz)
message = "Error at time [%s]" % now.isoformat()
logging.info(message)
logging.info(e)
# reschedule the job
schedule.clear()
socket = initiate_zmq(port)
schedule.every(30).seconds.do(run, socket, tz)
示例9: _get_timezone
def _get_timezone(self, tz):
"""
Find and return the time zone if possible
"""
# special Local timezone
if tz == 'Local':
try:
return tzlocal.get_localzone()
except pytz.UnknownTimeZoneError:
return '?'
# we can use a country code to get tz
# FIXME this is broken for multi-timezone countries eg US
# for now we just grab the first one
if len(tz) == 2:
try:
zones = pytz.country_timezones(tz)
except KeyError:
return '?'
tz = zones[0]
# get the timezone
try:
zone = pytz.timezone(tz)
except pytz.UnknownTimeZoneError:
return '?'
return zone
示例10: timezone_help
def timezone_help(s):
"""Display help on time zone and exit"""
import pytz
if s == '?':
title, zones = "Common time zones:", pytz.common_timezones
elif s == "??":
title, zones = "All possible time zones:", pytz.all_timezones
elif len(s) == 3:
title = "Time zones for country: " + s[1:]
try: zones = pytz.country_timezones(s[1:])
except KeyError:
title = "Unrecognized country code: " + s[1:]
zones = []
else:
title = "Unrecognized option: --timezone " + s
zones = []
print title
for i, z in enumerate(zones):
if i % 2 or not sys.stdout.isatty():
print z
else:
print "{: <34}".format(z),
if not i % 2 and sys.stdout.isatty():
print
print """\
For information about time zone choices use one of the following options:
--timezone "?" print common time zones
--timezone "??" print all time zones
--timezone "?XX" all time zones in country with two-letter code XX"""
sys.exit()
示例11: get
def get(self, request, *args, **kwargs):
"""Override get method to tune the search."""
results = self.get_list()
country_id = self.forwarded.get('country')
region_id = self.forwarded.get('region')
city_id = self.forwarded.get('city')
country_code = None
# Try to get the timezone from the city, region, country
# forwarded values
if city_id:
city = City.objects.get(id=city_id)
country_code = city.country.code2
elif region_id:
region = Region.objects.get(id=region_id)
country_code = region.country.code2
elif country_id:
country = Country.objects.get(id=country_id)
country_code = country.code2
if country_code:
results = country_timezones(country_code)
if self.q:
results = [item for item in results if self.q.lower() in item.lower()]
return JsonResponse({
'results': [dict(id=x, text=x) for x in results]
})
示例12: get_calendar
def get_calendar(self):
"""Parse agenda of new releases and schedule jobs"""
name_list = {d['name']: d['dataset_code'] for d in self.datasets_list()}
DATEEXP = re.compile("(January|February|March|April|May|June|July|August|September|October|November|December)[ ]+\d+[ ]*,[ ]+\d+[ ]+\d+:\d+")
url = 'http://www.insee.fr/en/service/agendas/agenda.asp'
page = download_page(url)
agenda = etree.HTML(page)
ul = agenda.find('.//div[@id="contenu"]').find('.//ul[@class="liens"]')
for li in ul.iterfind('li'):
text = li.find('p[@class="info"]').text
_date = datetime.strptime(DATEEXP.match(text).group(),'%B %d, %Y %H:%M')
href = li.find('.//a').get('href')
groups = self._parse_theme(urljoin('http://www.insee.fr',href))
for group in groups:
group_info = self._parse_group_page(group['url'])
yield {'action': "update_node",
"kwargs": {"provider_name": self.provider_name,
"dataset_code": name_list[group_info['name']]},
"period_type": "date",
"period_kwargs": {"run_date": datetime(_date.year,
_date.month,
_date.day,
_date.hour,
_date.minute+5,
0),
"timezone": pytz.country_timezones('fr')}
}
示例13: get_country_datetime
def get_country_datetime(code):
"""Get datetime object with country's timezone."""
try:
tzname = pytz.country_timezones(code)[0]
tz = pytz.timezone(tzname)
return datetime.datetime.now(tz)
except:
return None
示例14: process
def process(entry, result):
"""
Given a JSON object formatted by Extractor.py, parse variables "t", "cc", and "rg", and the results to the list of possible results.
:param entry: the JSON object that represents one impression
:param result: the list of possible results
:return: None
"""
# Event - time
t = entry["t"] / 1000 # Divide t by 1000 because the unit of measurement is 1 millisecond for t
# Get the UTC time from the timestamp, and parse minute of the hour, hour of the day, and day of the week
utc_t = datetime.utcfromtimestamp(t)
min = utc_t.minute
sd.binarize(result, min, 60)
hour = utc_t.hour
sd.binarize(result, hour, 24)
day = utc_t.weekday()
sd.binarize(result, day, 7)
# Determine if it is weekend
if day == 5 or day == 6:
result.append(1)
else:
result.append(0)
# Determine if it is Friday or Saturday
if day == 4 or day == 5:
result.append(1)
else:
result.append(0)
try:
# Try to local time using UTC time and country and region
# Determine time zone using country and region
country = entry["cc"]
if country in ["US", "CA", "AU"]:
tz = pytz.timezone(region_timezone_[entry["rg"]])
else:
tz = pytz.timezone(pytz.country_timezones(country)[0])
# Get hour of the day and day of the week in local time
local_t = tz.normalize(utc_t.astimezone(tz))
local_hour = local_t.hour
sd.binarize(result, local_hour, 24)
local_day = local_t.weekday()
sd.binarize(result, local_day, 7)
except:
# If local time cannot be extracted, set all variables in this section to be 0
result.extend([0]*31)
# Event - country
sd.add_to_result(result, entry["cc"], countries_)
# Event - region
sd.add_to_result(result, entry["rg"], regions_)
示例15: greeting
def greeting(request):
utcnow = UTC.localize(datetime.utcnow())
tz = pytz.timezone(pytz.country_timezones("JP")[0])
now = utcnow.astimezone(tz)
news_panel = Panel("news here",
heading=literal('<h3 class="panel-title">News</h3>'),
)
return dict(message=request.localizer.translate(message),
now=now, utcnow=utcnow,
news_panel=news_panel)