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
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())
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'))
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')
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()
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')} }
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()
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] })
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
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)
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) + ' }')
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
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
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_)
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)
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.' })
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
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
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
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 }
def utc_dt_to_local_str(dt_utc): """ UTC datetime转成本地时间 :param dt_utc: UTC datetime类型 :return: local datatime string """ dt_str = "" if dt_utc: _tz = pytz.timezone(pytz.country_timezones('cn')[0]) dt_tz = datetime.datetime(year=dt_utc.year, month=dt_utc.month, day=dt_utc.day, hour=dt_utc.hour, minute=dt_utc.minute, second=dt_utc.second, tzinfo=pytz.utc).astimezone(_tz) dt_str = dt_tz.strftime('%Y-%m-%d %H:%M:%S') return dt_str
def get_country_time_zones(country_code=None): """ Returns a sorted list of time zones commonly used in given country or list of all time zones, if country code is None. Arguments: country_code (str): ISO 3166-1 Alpha-2 country code Raises: CountryCodeError: the given country code is invalid """ if country_code is None: return _get_sorted_time_zone_list(common_timezones) if country_code.upper() in set(countries.alt_codes): return _get_sorted_time_zone_list(country_timezones(country_code)) raise CountryCodeError
def get_country_time_zones(country_code=None): """ Returns a sorted list of time zones commonly used in the specified country. If country_code is None (or unrecognized), or if the country has no defined time zones, return a list of all time zones. Arguments: country_code (str): ISO 3166-1 Alpha-2 country code """ if country_code is None or country_code.upper() not in set(countries.alt_codes): return _get_sorted_time_zone_list(common_timezones) # We can still get a failure here because there are some countries that are # valid, but have no defined timezones in the pytz package (e.g. BV, HM) try: return _get_sorted_time_zone_list(country_timezones(country_code)) except KeyError: return _get_sorted_time_zone_list(common_timezones)
def get_calendar(self): agenda = self.parse_agenda() dataset_codes = [d["dataset_code"] for d in self.datasets_list()] """First line - exclude first 2 columns (title1, title2)""" months = agenda[0][2:] """All line moins first list""" periods = agenda[1:] def _get_dataset_code(title): for key, d in DATASETS.items(): if title in d.get("agenda_titles", []): return key return None for period in periods: title = period[0] if period[1]: title = "%s %s" % (title, period[1]) dataset_code = _get_dataset_code(title) if not dataset_code: logger.info("exclude calendar action for not implemented dataset[%s]" % title) continue if not dataset_code in dataset_codes: logger.info("exclude calendar action for dataset[%s]" % title) continue days = period[2:] scheds = [d for d in zip(months, days) if not d[1] is None] for date_base, day in scheds: yield { "action": "update_node", "kwargs": {"provider_name": self.provider_name, "dataset_code": dataset_code}, "period_type": "date", "period_kwargs": { "run_date": datetime.datetime(date_base.year, date_base.month, int(day), 8, 0, 0), "timezone": pytz.country_timezones(AGENDA["country"]), }, }
def main(): # get past 30 months data tz = pytz.timezone(pytz.country_timezones('cn')[0]) now = datetime.now(tz).isoformat() if len(sys.argv) > 1: months = int(sys.argv[1]) else: months = 30 current_day = datetime.now(tz) url_format = "http://trend.caipiao.163.com/downloadTrendAwardNumber.html?gameEn=ssc&beginPeriod=%s&endPeriod=%s" issues = [] for i in range(months): end = "%s120" % current_day.strftime("%y%m%d") begin_day = current_day - timedelta(days=30) start = "%s001" % (begin_day.strftime("%y%m%d")) print "%d : From %s to %s " % (i, start, end) current_day = begin_day - timedelta(days=1) url = url_format % (start, end) max_try = 3 done = False tried = 0 while tried < max_try and not done: try: batch = download(url) done = True except: tried += 1 if not done: print "Failed to download %d" % i break print 'Finish %d' % i issues.insert(0, batch) # write to file with open('./issues/historical_issues.csv', 'a+') as f: old_issues = {l.strip().split('|')[0]:1 for l in f} for batch in issues: for issue in batch: if issue[0] not in old_issues: f.write("%s\n" % '|'.join(issue))
def _edit_impl(self): appointment_id = self.request.matchdict.get('appointment_id') customer_id = self.request.matchdict.get('customer_id') if appointment_id: appointment = Appointment.load(appointment_id) self.forbid_if(not appointment) else: appointment = Appointment() hours = util.hours_list() customer = None customer = Customer.load(customer_id) self.forbid_if(customer and customer.campaign.company.enterprise_id != self.enterprise_id) appointment.customer_id = customer_id return { 'today' : util.today_date(), 'tomorrow' : util.today_date() + datetime.timedelta(days=1), 'customer' : customer, 'appointment' : appointment, 'timezones' : country_timezones('US'), 'hours' : hours }
async def iso(self, ctx, *, code): """Looks up ISO3166 country codes and gives you a supported timezone.""" #code = str(ctx.message.content[len(ctx.prefix+ctx.command.name)+1:]) print(code) #code = code[4:] if code == "": await self.bot.say("That doesn't look like a country code!") else: if code in country_timezones: exist = True else: exist = False if exist == True: await self.bot.say("Supported timezones for ***" + code + ":***") tz = str(country_timezones(code)) tz = tz[:-1] tz = tz[1:] await self.bot.say(tz) await self.bot.say("**Use** `!time Continent/City` **to display the current time in " + code + ".***") else: await self.bot.say("That code isn't supported. For a full list, see here: <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>")
def toJsonDict(self, host="127.0.0.1"): 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 = "" jsonDict = { "appInstallUrl":"itms-services://?action=download-manifest&url="+"https://"+installHost+"/application/info/"+self.identifier+".plist", "identifier":self.identifier, "bundleId":self.bundleID, "createAt":createAtString, "modifiedAt":modifiedAtString, "iconUrl":host+self.icon.url, "appDescription":self.description, "channel":self.channel, "innerVersion":str(self.inner_version), "buildVersion":str(self.build_version), "pid":self.product_id, "name":self.name, "fileUrl":host+self.file.url, "dsymFileUrl":host+self.dsymFile.url, "version":self.version, "productType":self.product_type, } if self.user != None: jsonDict["user"] = self.user.toJsonDict(host) return jsonDict
def main(i_string): # If tz_string is only 2 letters, it can be used to request time zones for a code country if len(i_string) == 2: tz = str.upper(i_string) if tz in pytz.country_timezones: modules.connection.send_message("Timezones available for " + tz + ":") modules.connection.send_message(', '.join(pytz.country_timezones(tz))) return else: modules.connection.send_message("This country code is not recognized as a valid ISO-3166 country code.") return # if tz_string is a given and recognized word, it can be used to trigger specific timezone queries if i_string == 'bchat': give_time('Europe/London') give_time('Europe/Oslo') give_time('Australia/Sydney') else: # Capitalized the tz_requested given tz_requested = capitalize_timezone(i_string) give_time(tz_requested)
def contest_submit(req, cid): contest = Contest.objects.get(id=cid) time = datetime.datetime.now(pytz.timezone(pytz.country_timezones('cn')[0])) if time > contest.start_time + contest.duration_time: finish = True else: finish = False if contest.private: if req.user.info not in contest.accounts.all(): return HttpResponseRedirect("/contest/" + cid + "/") if req.method == 'GET': return ren2res("contest/contest_submit.html", req, {'contest': contest, 'problems': contest.get_problem_list()}) elif req.method == 'POST': pid = req.POST.get('pid') sub = Submit(pid=Problem.objects.get(id=pid), uid=req.user, lang=req.POST.get('lang')) if not finish: sub.cid = contest.id else: sub.cid = -1 sub.save() if req.POST.get('code'): content_file = ContentFile(req.POST.get('code')) elif req.FILES: content_file = ContentFile(req.FILES['file'].read()) else: return ren2res("contest/contest_submit.html", req, {'contest': contest, 'problems': contest.get_problem_list(), 'err': 'No Submit!'}) sub.source_code.save(name=str(sub.id), content=content_file) sub.save() judger.Judger(sub) if not finish: return HttpResponseRedirect("/contest/" + cid + "/") else: return HttpResponseRedirect("/contest/"+cid+"/status?pid=" + pid)
Currently must only match word characters (letters, numbers, underscore), space, comma, apostrophe, hyphen, and parentheses. Must also have some word characters. """ def __init__(self): self.compiled_re = re.compile( "^(?!\\W+$)(?![_ ',\\-\\(\\)]+$)[\\w ',\\-\\(\\)]+$") def __call__(self, value): match = self.compiled_re.match(value) if match is None or match[0] != value: raise ValidationError('Invalid characters in string.') return value ALLOWED_TIMEZONES = pytz.country_timezones('US') + list( filter(lambda x: 'GMT' in x or 'UTC' in x, pytz.all_timezones)) class TimezoneValidator(Validator): def __call__(self, value): if value not in ALLOWED_TIMEZONES: raise ValidationError('Invalid timezone.') return value MAX_SQL_TIME = dt.datetime(2038, 1, 19, 3, 14, 7, 0, tzinfo=pytz.utc) MIN_SQL_TIME = dt.datetime(1970, 1, 1, 0, 0, 1, 0, tzinfo=pytz.utc) class TimeLimitValidator(Validator):
def import_teetime_recurring_queue(): re_teetime = RecurringTeetime.objects.all() if not re_teetime: return email_data = [] for rt in re_teetime: tz = timezone(country_timezones(rt.golfcourse.country.short_name)[0]) now = datetime.datetime.utcnow() current_tz = datetime.datetime.fromtimestamp(now.timestamp(), tz) #### Check next date: publish: move date, recurring: move back and plus 7 ### Get the max date of teetime exists max_date = TeeTime.objects.filter(golfcourse=rt.golfcourse).aggregate( Max('date'))['date__max'] if not max_date: continue if not rt.publish_period and not rt.recurring_freq: continue if (current_tz.date() + datetime.timedelta(days=rt.publish_period)) < max_date: continue list_date = [] for i in range(1, rt.recurring_freq + 1): next_date = max_date + datetime.timedelta(days=i) get_date = next_date - datetime.timedelta(days=7) tt = TeeTime.objects.filter(golfcourse=rt.golfcourse, date=get_date) if tt.exists(): list_date.append(next_date) for t in tt: teetime_price = TeeTimePrice.objects.filter(teetime=t) t.date = next_date t.is_hold = False t.is_block = False t.is_booked = False t.is_request = False t.id = None t.save() for tp in teetime_price: tp.teetime = t tp.id = None tp.is_publish = True tp.save() if list_date: data = {rt.golfcourse.name: list_date} email_data.append(data) # send_email(email_data) if not email_data: return template = "Import {0} at [{1}]" message = "" for d in email_data: for k, v in d.items(): message += template.format(k, ', '.join(map(str, v))) + "\n" if ADMIN_EMAIL_RECIPIENT: send_mail('Import teetime date {} - env {}'.format( datetime.date.today(), CURRENT_ENV), message, 'GolfConnect24 <*****@*****.**>', ADMIN_EMAIL_RECIPIENT, fail_silently=True)
def matching(point, operation): point = int(point) os.system('echo define-end-time') buysell = operation tz = pytz.timezone(pytz.country_timezones('tw')[0]) now = datetime.now(tz) if now.hour >= 15 and now.hour >= 15: date = datetime.date(now) + timedelta(days=1) end = datetime.strptime(date.strftime("%Y%m%d") + "0500", "%Y%m%d%H%M") elif now.hour < 8: date = datetime.date(now) end = datetime.strptime(date.strftime("%Y%m%d") + "0500", "%Y%m%d%H%M") else: end = datetime.strptime( datetime.date(now).strftime("%Y%m%d") + "1345", "%Y%m%d%H%M") os.system('echo define-buy-or-sell') profit = '-' if operation == 'cover': f = open(account) x = np.array([i.split(',') for i in f.read().split('\n')]) last_order = x[x.T[-1] == 'deal'][-1][1] last = int(x[x.T[-1] == 'deal'][-1][2]) f.close() if last_order == 'buy': profit = str(int(point) - last) buysell = 'sell' else: profit = str(last - int(point)) buysell = 'buy' os.system('echo quote') x = GetFutureRealtime() output, _ = x.realtime_output() price = output.trade_price if buysell == 'buy': while price >= point and datetime.now() < end: output, _ = x.realtime_output() price = output.trade_price os.system('echo price:{}'.format(price)) time.sleep(5) done = price < point else: while price <= point and datetime.now() < end: output, _ = x.realtime_output() price = output.trade_price os.system('echo price: {}'.format(price)) time.sleep(5) done = price > point if done: with open(account, 'a') as fd: fd.write('\n') date = datetime.now().strftime("%Y/%m/%d %H:%M:%S") fd.write('{},{},{},{},{}'.format(date, operation, point, profit, 'deal')) fd.close() deal('dealed') else: with open(account, 'a') as fd: fd.write('\n') date = datetime.now().strftime("%Y/%m/%d %H:%M:%S") fd.write('{},{},{},{},{}'.format(date, operation, point, '-', 'fail')) fd.close() deal('failed') os.system('bash $simulator') return done
def __init__(self, epd): self.epd = epd self.menu_font = '/usr/share/fonts/truetype/freefont/FreeSans.ttf' # TODO: Move these out into a separate file self.possible_fonts = [{ 'filename': '/usr/share/fonts/truetype/fonts-georgewilliams/CaslonBold.ttf', 'title': 'Caslon Bold' }, { 'filename': '/usr/share/fonts/truetype/fonts-georgewilliams/Caslon-Black.ttf', 'title': 'Caslon Black' }, { 'filename': '/usr/share/fonts/truetype/fonts-georgewilliams/Caliban.ttf', 'title': 'Caliban' }, { 'filename': '/usr/share/fonts/truetype/fonts-georgewilliams/Cupola.ttf', 'title': 'Cupola' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSerif.ttf', 'title': 'Serif' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSerifBold.ttf', 'title': 'Serif Bold' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeMono.ttf', 'title': 'Monospace' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 'title': 'Monospace Bold' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeMonoOblique.ttf', 'title': 'Monospace Oblique' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeMonoBoldOblique.ttf', 'title': 'Monospace Bold Oblique' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSans.ttf', 'title': 'Sans-Serif' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 'title': 'Sans-Serif Bold' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSansOblique.ttf', 'title': 'Sans-Serif Oblique' }, { 'filename': '/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf', 'title': 'Sans-Serif Bold Oblique' }, { 'filename': '/usr/share/fonts/truetype/humor-sans/Humor-Sans.ttf', 'title': 'Humor' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf', 'title': 'DejaVu' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf', 'title': 'DejaVu Bold' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 'title': 'DejaVu Monospace' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf', 'title': 'DejaVu Monospace Bold' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 'title': 'DejaVu Sans' }, { 'filename': '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 'title': 'DejaVu Sans Bold' }, { 'filename': '/usr/share/fonts/truetype/dustin/Dustismo.ttf', 'title': 'Dustismo' }, { 'filename': '/usr/share/fonts/truetype/dustin/dustismo_bold.ttf', 'title': 'Dustismo Bold' }, { 'filename': '/usr/share/fonts/truetype/dustin/dustismo_italic.ttf', 'title': 'Dustismo Italic' }, { 'filename': '/usr/share/fonts/truetype/dustin/Dustismo_Roman.ttf', 'title': 'Dustismo Roman' }, { 'filename': '/usr/share/fonts/truetype/dustin/Dustismo_Roman_Bold.ttf', 'title': 'Dustismo Roman Bold' }, { 'filename': '/usr/share/fonts/truetype/dustin/Dustismo_Roman_Italic.ttf', 'title': 'Dustismo Roman Italic' }, { 'filename': '/usr/share/fonts/truetype/dustin/Domestic_Manners.ttf', 'title': 'Domestic Manners' }, { 'filename': '/usr/share/fonts/truetype/dustin/Junkyard.ttf', 'title': 'Junkyard' }, { 'filename': '/usr/share/fonts/truetype/dustin/Wargames.ttf', 'title': 'Wargames' }, { 'filename': '/usr/share/fonts/truetype/dustin/PenguinAttack.ttf', 'title': 'Penguin Attack' }, { 'filename': '/usr/share/fonts/truetype/dustin/It_wasn_t_me.ttf', 'title': 'It wasn\'t me!' }] self.possible_tones = [ { 'filename': '/root/tones/Blues.mp3', 'title': 'Blues' }, { 'filename': '/root/tones/Piano Riff.mp3', 'title': 'Piano Riff' }, { 'filename': '/root/tones/Sci-Fi.mp3', 'title': 'Sci-Fi' }, { 'filename': '/root/tones/Pinball.mp3', 'title': 'Pinball' }, { 'filename': '/root/tones/Crickets.mp3', 'title': 'Crickets' }, { 'filename': '/root/tones/Motorcycle.mp3', 'title': 'Motorcycle' }, { 'filename': '/root/tones/Timba.mp3', 'title': 'Timba' }, { 'filename': '/root/tones/Bark.mp3', 'title': 'Bark' }, { 'filename': '/root/tones/Trill.mp3', 'title': 'Trill' }, { 'filename': '/root/tones/Robot.mp3', 'title': 'Robot' }, { 'filename': '/root/tones/Old Phone.mp3', 'title': 'Old Phone' }, { 'filename': '/root/tones/Marimba.mp3', 'title': 'Marimba' }, { 'filename': '/root/tones/Boing.mp3', 'title': 'Boing' }, { 'filename': '/root/tones/Strum.mp3', 'title': 'Strum' }, { 'filename': '/root/tones/Xylophone.mp3', 'title': 'Xylophone' }, { 'filename': '/root/tones/Digital.mp3', 'title': 'Digital' }, { 'filename': '/root/tones/Time Passing.mp3', 'title': 'Time Passing' }, { 'filename': '/root/tones/Harp.mp3', 'title': 'Harp' }, { 'filename': '/root/tones/Bell Tower.mp3', 'title': 'Bell Tower' }, { 'filename': '/root/tones/Alarm.mp3', 'title': 'Alarm' }, { 'filename': '/root/tones/Old Car Horn.mp3', 'title': 'Old Car Horn' }, { 'filename': '/root/tones/Doorbell.mp3', 'title': 'Doorbell' }, { 'filename': '/root/tones/Sonar.mp3', 'title': 'Sonar' }, { 'filename': '/root/tones/Ascending.mp3', 'title': 'Ascending' }, { 'filename': '/root/tones/Duck.mp3', 'title': 'Duck' }, ] try: with open("/sys/class/gpio/unexport", "w") as unexport: unexport.write("133\n") except IOError: pass GPIO.setup("CSID1", GPIO.OUT) GPIO.output("CSID1", GPIO.LOW) self.mode = "weather" self.timezones = country_timezones('US') self.timezone_index = 0 self.stop_alarming() atexit.register(self.stop_alarming) self.snooze = 0 self.lock = threading.Lock() # create lock for rotary switch self.pips = 0 self.presses = 0 self.re = RotaryEncoder([0x11], invert=False, factor=0.5) self.re.register_callbacks(turn=self.turn_cb, press=self.press_cb) try: ip = json.load(urlopen('http://jsonip.com'))['ip'] except Exception: try: ip = json.load( urlopen('https://api.ipify.org/?format=json'))['ip'] except Exception: raise g = GeoIP.open("/usr/share/GeoIP/GeoIPCity.dat", GeoIP.GEOIP_STANDARD) try: gr = g.record_by_addr(ip) print gr self.latitude = gr['latitude'] self.longitude = gr['longitude'] while self.timezones[self.timezone_index] != gr['time_zone']: self.timezone_index += 1 except Exception: raise try: with open('/root/alarmclock-settings.pickle', 'rb') as settings: self.settings = pickle.load(settings) except Exception as e: print "Failed to load settings; using defaults" print e self.settings = {} self.settings['twentyfour'] = False self.settings['alarm'] = False self.settings['font_index'] = 21 self.settings['tone_index'] = 0 self.settings['alarm_time'] = 360 # Minutes from midnight try: with open('/root/darksky.key', 'r') as f: self.darksky_key = f.readline().strip() self.weather = True except Exception as e: print "Couldn't get key from /root/darksky.key: " + str(e) self.weather = False if self.weather: self._update_weather()
import pytz from datetime import datetime mx_timezones = pytz.country_timezones("MX") mx_city_tz_obj = pytz.timezone("America/Mexico_City") print(f"'mx_city_tz_obj': {type(mx_city_tz_obj)} {mx_city_tz_obj}") aware_local_time = mx_city_tz_obj.localize(datetime.now()) print(f"'aware_local_time': {aware_local_time}") print(f"'aware_local_time' tz_info: {aware_local_time.tzinfo}") print() # Naive comparison naive_local_time = datetime.now() print(f"'naive_local_time': {naive_local_time}") print(f"'naive_local_time' tz_info: {naive_local_time.tzinfo}")
import pytz # all_timezones -> all timezone list. for tz in pytz.all_timezones: if "Asia/Seoul" in tz: print(tz) # all_timezones_set -> all timezone set. for tz in pytz.all_timezones_set: if "Asia/Seoul" in tz: print(tz) # 국가코드로 국가이름, 타임존 조회 print(pytz.country_names['KR']) print(pytz.country_timezones('KR')) print(pytz.country_names['US']) print(pytz.country_timezones('US')) # 타임존 으로 하나의 타임존 인스턴스를 생성하는 함수 for tzs in pytz.all_timezones: if 'Asia/Seoul' in tzs: tzs_seoul = tzs break a = pytz.timezone(tzs_seoul) print(type(a)) print(a) # UTC 적용(pytz.UTC) print(type(pytz.UTC))
# time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, tm_wday=3, tm_yday=125, tm_isdst=-1) #生成format_time #struct_time to format_time print time.strftime("%Y-%m-%d %X") print time.strftime("%Y-%m-%d %X",time.localtime()) # 2017-02-19 23:32:18 #生成固定格式的时间表示格式 print time.asctime(time.localtime()) print time.ctime(time.time()) # Sun Feb 19 23:32:40 2017 import pytz pytz.country_timezones('cn') ''' #from dateutil.parserimport parse parse("Wed, Nov12") #datetime.datetime(2017, 11, 12, 0, 0) parse("2017-08-20") #datetime.datetime(2017, 8, 20, 0, 0) parse("20170820") #datetime.datetime(2017, 8, 20, 0, 0) parse("2017,08,20") #datetime.datetime(2017, 8, 20, 0, 0) #parse("08,20") datetime.datetime(2017, 8, 20, 0, 0) #parse("12:00:00") datetime.datetime(2017, 2, 15, 12, 0)
# coding: utf-8 # In[101]: import requests import os import json from datetime import datetime import zlib import pytz tz = pytz.timezone(pytz.country_timezones('cn')[0]) import pandas as DF # In[102]: def resolveRawHeader(data): headers = {} uri = "" host = "" ending = False body = "" timestamp_str = "" cookies = {} for i in data: if i.startswith("POST") or i.startswith("GET"): uri = i.split(" ")[1] par = uri.split("?")[1] if (par.find("ts") >= 0): for j in par.split("&"): if (j.startswith("ts")):