• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pytz.country_timezones函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pytz.country_timezones函数的典型用法代码示例。如果您正苦于以下问题:Python country_timezones函数的具体用法?Python country_timezones怎么用?Python country_timezones使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了country_timezones函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:pierxco,项目名称:djel,代码行数:7,代码来源:tz_detector.py


示例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())
开发者ID:wasw100,项目名称:test,代码行数:32,代码来源:date_test.py


示例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'))
开发者ID:Officium,项目名称:SomeTest,代码行数:14,代码来源:dates+and+times.py


示例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')
开发者ID:gaopinghuang0,项目名称:learn-python,代码行数:15,代码来源:chap3-number-date-time.py


示例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
开发者ID:kelvinn,项目名称:helomx,代码行数:7,代码来源:__init__.py


示例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()
开发者ID:electricface,项目名称:deepin-system-settings,代码行数:30,代码来源:provider.py


示例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) + ' }')
开发者ID:dalgibbard,项目名称:localhour,代码行数:32,代码来源:app.py


示例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)
开发者ID:Tskatom,项目名称:Lottery,代码行数:27,代码来源:ingest_lottery.py


示例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
开发者ID:mrt-prodz,项目名称:py3status,代码行数:27,代码来源:clock.py


示例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()
开发者ID:svetlyak40wt,项目名称:dayone_export,代码行数:33,代码来源:dayone_export.py


示例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]
        })
开发者ID:johngian,项目名称:mozillians,代码行数:30,代码来源:views.py


示例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')}
                  }
开发者ID:ThomasRoca,项目名称:dlstats,代码行数:28,代码来源:insee.py


示例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
开发者ID:DarkDefender,项目名称:scripts,代码行数:8,代码来源:country.py


示例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_)
开发者ID:Shurooo,项目名称:gumgum,代码行数:57,代码来源:Event.py


示例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)
开发者ID:rebeccaframework,项目名称:rebecca.bootstrapui,代码行数:11,代码来源:hello.py


示例16: save_timezone

def save_timezone():
    if current_user and current_user.is_active():
        timezone = unicode(request.form.get("timezone")).strip()
        if timezone in pytz.country_timezones("US"):
            current_user.timezone = timezone
            current_user.save()
            return jsonify({ 'message' : 'Timezone updated.' })
        else:
            return jsonify({ 'message' : 'Unrecognized timezone, please try again.' })
    else:
        return jsonify({ 'message' : 'Error updating timezone, please try again.' })
开发者ID:Bobfrat,项目名称:alerting,代码行数:11,代码来源:session.py


示例17: get_user_timezone

def get_user_timezone(request):
    ip_addr = request.META['REMOTE_ADDR']
    user_timezone = settings.TIME_ZONE

    geoip = GeoIP()
    country_code = geoip.country(ip_addr).get('country_code')
    if country_code:
        timezones = country_timezones(country_code)
        user_timezone = timezones[0] if timezones else user_timezone

    return user_timezone
开发者ID:bogdal,项目名称:flickrgeotagger,代码行数:11,代码来源:geoip_timezone.py


示例18: toJsonDict

    def toJsonDict(self, host="127.0.0.1"):
# platform_choices = (
#                     (0,_(u"通用")),
#                     (1,_(u"iOS")),
#                     (2,_(u"Android")),
#                     (999,_(u"其他")),
#                    )
        platformText = "通用"
        if self.platform == 1:
            platformText = "iOS"
        elif self.platform == 2:
            platformText = "Android"
        elif self.platform == 999:
            platformText = "其他"

        installHost = host
        if "http://" in host:
            installHost = host.split("http://")[1]

        tz = pytz.timezone(pytz.country_timezones('cn')[0])

        createAtString = str(self.create_at.fromtimestamp(self.create_at.timestamp(), tz).strftime("%Y-%m-%d %H:%M:%S"))
        if createAtString == None:
            createAtString = ""

        modifiedAtString = str(self.modified_at.fromtimestamp(self.modified_at.timestamp(), tz).strftime("%Y-%m-%d %H:%M:%S"))
        if modifiedAtString == None:
            modifiedAtString = ""


        retJsonDict = {
                    "latestAppIdentifier":self.applications.last().identifier,
                    "latestAppInstallUrl":"itms-services://?action=download-manifest&url="+"https://"+installHost+"/application/info/"+self.applications.last().identifier+".plist",
                    "identifier":self.identifier,
                    "bundleId":self.bundleID,
                    "createAt":createAtString,
                    "modifiedAt":modifiedAtString,
                    "iconUrl":host+self.icon.url,
                    "productDescription":self.description,
                    "latestVersion":self.latest_version,
                    "latestInnerVersion":str(self.latest_inner_version),
                    "latestBuildVersion":str(self.latest_build_version),
                    "pid":self.product_id,
                    "platform":platformText,
                    "name":self.name,
                    "status":self.product_status,
                    "productType":self.product_type,
                }
        if self.owner != None:
            retJsonDict["ownner"] = self.owner.toJsonDict(host)

        return retJsonDict
开发者ID:gao7ios,项目名称:G7Platform,代码行数:52,代码来源:models.py


示例19: getMostRecentlyUsedTerms

 def getMostRecentlyUsedTerms(self):
     mru = super(TimeZoneWidget, self).getMostRecentlyUsedTerms()
     # add ones from locale
     territory = self.request.locale.id.territory
     if territory:
         try:
             choices = pytz.country_timezones(territory)
         except KeyError:
             pass
         else:
             already = set(term.token for term in mru)
             additional = sorted(t for t in choices if t not in already)
             mru.extend(zc.form.interfaces.Term(t.replace('_', ' '), t)
                          for t in additional)
     return mru
开发者ID:zopefoundation,项目名称:zc.form,代码行数:15,代码来源:tzwidget.py


示例20: _edit_impl

 def _edit_impl(self, user_id=None):
     user = priv = None
     if user_id:
         user = self.request.ctx.user if self.request.ctx.user.user_id == user_id else Users.load(user_id)
         priv = user.priv if user.priv else UserPriv()
     else:
         user = Users()
         priv = UserPriv()
     return {
         'enterprises' : util.select_list(Enterprise.find_all(), 'enterprise_id', 'name', True),
         'user_types': Users.get_user_types(),
         'vendors' : util.select_list(Vendor.find_all(self.enterprise_id), 'vendor_id', 'name', True),
         'timezones' : country_timezones('US'),
         'user' : user,
         'priv' : priv
         }
开发者ID:anonymoose,项目名称:pvscore,代码行数:16,代码来源:users.py



注:本文中的pytz.country_timezones函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pytz.timezone函数代码示例发布时间:2022-05-27
下一篇:
Python parser.parse_string函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap