def checkio(from_date, to_date): result = 0 while from_date != date.fromordinal(to_date.toordinal() + 1): if from_date.weekday() > 4: result += 1 from_date = date.fromordinal(from_date.toordinal() + 1) return result
def initialize1( self,stockTicker, date1, date2, interval, resolution, dataFeedType): self.stockTicker = stockTicker; if(dataFeedType =="yahoo"): self.quotes = quotes_historical_yahoo(self.stockTicker, date1, date2) self.N = self.quotes.__len__(); self.vDateInt = zeros(self.N) self.vDate = empty(self.N, dtype=object); self.vOpen = zeros(self.N) self.vClose = zeros(self.N) self.vHigh = zeros(self.N) self.vLow = zeros(self.N) self.vVolume = zeros(self.N) index = 0; for line in self.quotes: self.vDateInt[index]= line [0]; self.vDate[index] = date.fromordinal( int( line [0] ) ) self.vOpen[index] = line [1]; self.vClose[index] = line [2]; self.vHigh[index] = line [3]; self.vLow[index] = line [4]; self.vVolume[index] = line [5]; index = index +1; elif (dataFeedType == "google"): self.vDateInt, self.vOpen, self.vHigh, self.vLow, self.vClose, self.vVolume = quotes_historical_google.getData(symbol=self.stockTicker, startDate=date1, endDate=date2, resolution=resolution); self.N = size(self.vDateInt); self.vDate = empty(self.N, dtype=object); index = 0; for d in self.vDateInt: self.vDate[index] = date.fromordinal( int( d) ); index = index + 1;
def main(start_ord, end_ord): print "start_ord: %d, end_ord: %d" % (start_ord, end_ord) first_sunday_ord = 0 datearr = [] for day_ord in range(start_ord, start_ord + 7): # find the first Sunday within the range dt = date.fromordinal(day_ord) if 'Sun' in dt.ctime(): first_sunday_ord = day_ord # print dt.ctime() break st = date.fromordinal(first_sunday_ord) print st.ctime() # return pat = re.compile(r'Sun [\w]{3} 1 .*') # st = 'Sun Jan 1 00:00:00 1901' # if pat.match(st): # print "OK" sundays_counted = 0 for day_ord in range(first_sunday_ord, end_ord, 7): # count the Sundays that are on the first # print "day_ord: %d, first_sunday_ord: %d, ctime: %s" % (day_ord. first_sunday_ord, dt.ctime()) dt = date.fromordinal(day_ord) if pat.match(dt.ctime()): print dt.ctime() sundays_counted += 1 # print first_sunday_ord = day_ord print "sundays_counted: %d" % sundays_counted
def dateCode(iDate): rDate = [] Date = iDate.upper() global TodaysDate # if a single letter code is entered, return the associated date if len(Date) == 1: code = codeToNum(Date) fDate = date.fromordinal(TodaysDate.toordinal() + code) rDate.append(fDate) return rDate # if a code for a next week date is entered, returns associated date elif Date[0:1] == 'N': code = codeToNum(Date[1:2]) code += 7 fDate = date.fromordinal(TodaysDate.toordinal() + code) rDate.append(fDate) return rDate # if a code for multiple dates is entered, returns associated dates elif Date[0:1].isdigit(): lNum = re.findall(r'\d+', Date) iNum = int(lNum[0]) # if code is two digits if iNum>=10: code = codeToNum(Date[2:3]) # if code is a single digit else: code = codeToNum(Date[1:2]) fDate = date.fromordinal(TodaysDate.toordinal() + code) rDate.append(fDate) # append dates for day of each week for the number of weeks designated for i in range(1,iNum): code += 7 fDate = date.fromordinal(TodaysDate.toordinal() + code) rDate.append(fDate) return rDate
def handle(self, *args, **options): _fields_to_update = ["Joomla Paid Count"] joomla = JoomlaInterface(settings.JOOMLA_USER, settings.JOOMLA_PASSWORD) joomla.authenticate() if options['year']: year = options['year'] month = options['month'] _start_date = date(year, month, 1) _end_date = date.fromordinal(date(year, month + 1, 1).toordinal() - 1) _schedules = ProgramSchedule.objects.filter(start_date__gte=_start_date, end_date__lte=_end_date) else: reference_date = date.fromordinal(date.toordinal(date.today()) - 50) _schedules = ProgramSchedule.objects.filter(start_date__gte=reference_date) for each_schedule in _schedules: if not each_schedule.online_registration_code: continue if each_schedule.online_registration_code.startswith("FAILED"): continue print(each_schedule) paid_count = joomla.get_paid_count(each_schedule.online_registration_code) print("%d paid for %s" % (paid_count, each_schedule.online_registration_code)) _create_or_update(_fields_to_update, (paid_count,), each_schedule)
def get_monthly_totals(self, start, end, paid): # Return a list of categories and totals for the given month ret = [] records = self.actions.get_monthly_totals(date.fromordinal(start), date.fromordinal(end), paid) for record in records: ret.append(record) return ret
def aluguelreserv(nomeCliente = None, cpfCliente = None): clientes = shelve.open("clientes.pyc") #Clientes eh o ARQUIVO for c in clientes: if clientes[c].nome == nomeCliente: if cpfCliente != None and clientes[c].cpf == cpfCliente: c = clientes[c] break else: return "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.", False if c.filmesReservados[nomeFilme]["DataAluguel"] == date.today(): for nomeFilme in c.filmesReservados: dataDevolucao = date.fromordinal(date.toordinal(dataAluguel)+len(c.filmesReservados)) #Data na qual o DVD esta sendo alugado baseado na quantidade de filmes reservados if diaDevolucao == 6: dataDevolucao = date.fromordinal(date.toordinal(dataDevolucao)+1) c.filmesAlugados[nomeFilme] = c.filmesReservados[nomeFilme] c.filmesAlugados[nomeFilme]["DataDevolucao"] = "%d-%d-%d" %(dataDevolucao.date,dataDevolucao.month,dataDevolucao.year) c.filmesReservados = {} return "Aluguel efetuado com exito", valor, True else: return "Filme reservado para o dia: ",c.filmesReservados[nomeFilme]["DataAluguel"], False
def DelVmReten(vm, TIME_LIMIT, SLEEP, retencao, day, dias): try: TIME_WAITING = 0 try: reten = retencao[vm.name] except: reten = 1 ant = date.fromordinal(day.toordinal() - reten) day_ant = dias[ant.weekday()] number_day_ant = date.fromordinal(day.toordinal() - reten).day number_month_ant = date.fromordinal(day.toordinal() - reten).month VM_BKP_ANT = vm.name + '-%s-%s-%s' % (day_ant, number_day_ant, number_month_ant) logging.info('Verificando se VM %s existe' % VM_BKP_ANT) if api.vms.get(VM_BKP_ANT): api.vms.get(VM_BKP_ANT).delete() while True: if api.vms.get(VM_BKP_ANT): time.sleep(SLEEP) else: break if TIME_WAITING >= TIME_LIMIT: logging.error('ERROR: VM nao deletada apos %s segundos' % TIME_LIMIT, exc_info=True) raise TIME_WAITING += SLEEP logging.info('%s removida com sucesso ' % VM_BKP_ANT) else: logging.info('%s nao existe ' % VM_BKP_ANT) return True except Exception as e: logging.error('Falha ao remover \n%s' % str(e), exc_info=True) return False
def save_to_pgsql(self, connection, table_name='"Municipio"."Notificacao"'): print("Escrevendo no PostgreSQL...") ano = self.time_span[1].year if self.time_span[0] == self.time_span[1] else self.ano geoclist_sql = ",".join([str(gc) for gc in self.geocodigos]) with connection.cursor(cursor_factory=DictCursor) as cursor: cursor.execute("select * from {} limit 1;".format(table_name)) col_names = [c.name for c in cursor.description if c.name != "id"] self._fill_missing_columns(col_names) df_names = [field_map[n] for n in col_names] insert_sql = 'INSERT INTO {}({}) VALUES ({}) on conflict on CONSTRAINT casos_unicos do UPDATE SET {}'. \ format(table_name, ','.join(col_names), ','.join(['%s' for i in col_names]), ','.join(['{0}=excluded.{0}'.format(j) for j in col_names])) for row in self.tabela[df_names].iterrows(): i = row[0] row = row[1] row[0] = None if isinstance(row[0], pd.tslib.NaTType) else date.fromordinal( row[0].to_datetime().toordinal()) # dt_notific row[1] = int(str(int(row[1]))[-2:]) # se_notific row[2] = int(self.ano) if pd.isnull(row[2]) else int(row[2]) # ano_notific row[3] = None if isinstance(row[3], pd.tslib.NaTType) else date.fromordinal( row[3].to_datetime().toordinal()) # dt_sin_pri row[4] = None if not row[4] else int(str(row[4])[-2:]) # se_sin_pri row[5] = None if isinstance(row[5], pd.tslib.NaTType) else date.fromordinal( row[5].to_datetime().toordinal()) # dt_digita row[7] = None if not row[7] else int(row[7]) # bairro_bairro_id row[8] = None if row[8] == '' else add_dv(int(row[8])) # municipio_geocodigo row[9] = int(row[9]) # nu_notific cursor.execute(insert_sql, row) if (i % 1000 == 0) and (i > 0): connection.commit() connection.commit()
def reset(self): self.EF = 2.5 self.repeat = 0 self.interval = 0 self.initDate = date.fromordinal(1) self.startDate = date.fromordinal(1) self.nextDate = date.fromordinal(1)
def __setstate__(self, state: Dict[str, Any]): if state['version'] > 1: raise ValueError('cannot deserialize {} definition newer than version 1 (version {} ' 'received)'.format(self.__class__.__name__, state['version'])) super().__setstate__(state) self.years, self.months, self.weeks, self.days = state['interval'] self.time = (time(*state['time']) if 'time' in state else time()) self.start_date = date.fromordinal(state['start_date']) if 'start_date' in state else None self.end_date = date.fromordinal(state['end_date']) if 'end_date' in state else None
def __check_date(thedate): weekday = thedate.weekday() if weekday >= 5: print("Error: given date is on a weekend. Please try {0} or {1} instead.".format(\ date.fromordinal(thedate.toordinal()+(7-weekday)),\ date.fromordinal(thedate.toordinal()-(weekday-4))\ ),file=sys.stderr) exit(1) else: return thedate in menu
def get_working_days(start, end, week_days_off=None): """Returns a list of working days within the given interval, start and end are passed either as datetimes, dates or ordinal values.""" if start is not None and end is not None: if isinstance(start, (date, datetime)) and isinstance(end, (date, datetime)): # passed dates are date values return _compute_interval(start, end=end, week_days_off=week_days_off) elif isinstance(start, int) and isinstance(end, int): # passed dates are ordinal values return _compute_interval(date.fromordinal(start), end=date.fromordinal(end), week_days_off=week_days_off) return []
def get_days_of_week(self, start_date, end_date, day_of_week): """ First convert start_date and end_date to have the day of week we require. Then get all the dates of the specified day of week between the start_date and end_date. """ start_date = start_date - timedelta(days=(start_date.weekday() - day_of_week)) end_date = end_date - timedelta(days=(end_date.weekday() - day_of_week)) for ordinal in range(start_date.toordinal(), end_date.toordinal() + 1): if date.fromordinal(ordinal).weekday() == day_of_week: yield date.fromordinal(ordinal)
def Run(input_nc, output_nc, input_JRC): # Define names #Name_py_Discharge_dict_CR2 = os.path.join(Dir_Basin, 'Simulations', 'Simulation_%d' %Simulation, 'Sheet_5', 'Discharge_dict_CR2_simulation%d.npy' %(Simulation)) #Name_py_River_dict_CR2 = os.path.join(Dir_Basin, 'Simulations', 'Simulation_%d' %Simulation, 'Sheet_5', 'River_dict_CR2_simulation%d.npy' %(Simulation)) #Name_py_DEM_dict_CR2 = os.path.join(Dir_Basin, 'Simulations', 'Simulation_%d' %Simulation, 'Sheet_5', 'DEM_dict_CR2_simulation%d.npy' %(Simulation)) #Name_py_Distance_dict_CR2 = os.path.join(Dir_Basin, 'Simulations', 'Simulation_%d' %Simulation, 'Sheet_5', 'Distance_dict_CR2_simulation%d.npy' %(Simulation)) #if not (os.path.exists(Name_py_Discharge_dict_CR2) and os.path.exists(Name_py_River_dict_CR2) and os.path.exists(Name_py_DEM_dict_CR2) and os.path.exists(Name_py_Distance_dict_CR2)): # Copy dicts as starting adding reservoir import wa.General.raster_conversions as RC import numpy as np from datetime import date Discharge_dict_CR2 = RC.Open_nc_dict(output_nc, "dischargedict_dynamic") DEM_dataset = RC.Open_nc_array(input_nc, "dem") time = RC.Open_nc_array(output_nc, "time") Startdate = date.fromordinal(time[0]) Enddate = date.fromordinal(time[-1]) # Define names for reservoirs calculations #Name_py_Diff_Water_Volume = os.path.join(Dir_Basin,'Simulations','Simulation_%d' %Simulation, 'Sheet_5','Diff_Water_Volume_CR2_simulation%d.npy' %(Simulation)) #Name_py_Regions = os.path.join(Dir_Basin,'Simulations','Simulation_%d' %Simulation, 'Sheet_5','Regions_simulation%d.npy' %(Simulation)) geo_out, proj, size_X, size_Y = RC.Open_array_info(input_JRC) Boundaries = dict() Boundaries['Lonmin'] = geo_out[0] Boundaries['Lonmax'] = geo_out[0] + size_X * geo_out[1] Boundaries['Latmin'] = geo_out[3] + size_Y * geo_out[5] Boundaries['Latmax'] = geo_out[3] Regions = Calc_Regions(input_nc, output_nc, input_JRC, Boundaries) Amount_months = len(Discharge_dict_CR2[0]) Diff_Water_Volume = np.zeros([len(Regions), Amount_months, 3]) reservoir=0 for region in Regions: popt = Find_Area_Volume_Relation(region, input_JRC, input_nc) Area_Reservoir_Values = GEE_calc_reservoir_area(region, Startdate, Enddate) Diff_Water_Volume[reservoir,:,:] = Calc_Diff_Storage(Area_Reservoir_Values, popt) reservoir+=1 ################# 7.3 Add storage reservoirs and change outflows ################## Discharge_dict_CR2, River_dict_CR2, DEM_dict_CR2, Distance_dict_CR2 = Add_Reservoirs(output_nc, Diff_Water_Volume, Regions) return(Discharge_dict_CR2, River_dict_CR2, DEM_dict_CR2, Distance_dict_CR2)
def _get_lastProperSearch(): """ Find last propersearch from DB """ sqlResults = main_db.MainDB().select("SELECT * FROM info") try: last_proper_search = date.fromordinal(int(sqlResults[0][b"last_proper_search"])) except: return date.fromordinal(1) return last_proper_search
def __repr__(self): return "<ServicePeriod %s %s%s%s%s%s%s%s %s %s>" % ( self.service_id, self.monday, self.tuesday, self.wednesday, self.thursday, self.friday, self.saturday, self.sunday, date.fromordinal(self.start_date), date.fromordinal(self.end_date), )
def num_guardias_total_hasta_fin_mes_asignadas(self, hoy): from guardias.models import Guardia import calendar añoc = date.fromordinal(hoy).year mesc = date.fromordinal(hoy).month inicio = date(añoc, 1, 1).toordinal() fin = date(añoc, mesc, calendar.monthrange(añoc, mesc)[1]).toordinal() return Guardia.objects.filter( owner = self ).filter( fecha__gte=inicio ).filter( fecha__lte=fin ).count()
def browse_mode(CardList, today): index = 0 len_list = len(CardList) while len_list > 0: #pdb.set_trace() index %= len_list card = CardList[index] print '------(', index + 1, ')-------' card.getcard() print '-----------------' # Input command for each card to init or reset it. while True: subcommand = raw_input(\ '(a)dd|(r)eset|(e)xit|(i)nfo, "enter key" to go next: ') if subcommand == 'a': if card.initDate == date.fromordinal(1): card.add(today) print 'This card is added' else: print 'This card has already been added' elif subcommand == 'r': if card.initDate == date.fromordinal(1): print 'This card has already been reset' else: card.reset() print 'This card is reseted' elif subcommand == 'i': card.getcard_info() elif subcommand == 'p': index -= 1 break elif subcommand == 'e': break elif subcommand == '': index += 1 break else: print("Oops... ") if subcommand == 'e': break
def _confirmday(self, backupday): """ backupday may be ... 1. date object 2. string looking like a date 3. int or number coercible to an integer being pre or post today If it is a valid date look at smallhours in relation to the current time to see whether to use yesterday or today as a label. Note: This will permit smallhours to affect future dates. """ try: # test for an integer and if so, add it to date.today() x = int(backupday) self.increment = x # this naturally defeats smallhours return date.fromordinal(date.today().toordinal() + self.increment) except Exception: # might have been a real date or a date in a string try: # None or '' is a pseudo-default to today if backupday is None or backupday == "": backupday = date.today() else: # looks like a date in a string guess = guessdate(backupday) # if it crashes the exception is raised in guessdate backupday = guess except Exception: pass try: # after crashing at int(backupday) above, backupday is now valid # but if guessdate crashed ... this will too ordbackupdate = backupday.toordinal() except Exception: raise ValueError("Invalid date") # and abandon # here we have a valid backupday and valid ordbackupday if self.smallhours > 0: hrs = datetime.now().timetuple()[3] if hrs < self.smallhours: # yesterday please return date.fromordinal(ordbackupdate - 1) # must return a proper datetime object if backupday == date.today(): return date.fromordinal(date.today().toordinal() + self.increment) return backupday or date.today()
def save_to_pgsql(self, table_name='"Municipio"."Notificacao"', default_cid=None): connection = self._get_postgres_connection() logger.info("Escrevendo no PostgreSQL") ano = self.time_span[1].year if self.time_span[0] == self.time_span[1] else self.ano geoclist_sql = ",".join([str(gc) for gc in self.geocodigos]) with connection.cursor(cursor_factory=DictCursor) as cursor: cursor.execute("select * from {} limit 1;".format(table_name)) col_names = [c.name for c in cursor.description if c.name != "id"] self._fill_missing_columns(col_names) df_names = [field_map[n] for n in col_names] insert_sql = 'INSERT INTO {}({}) VALUES ({}) on conflict on CONSTRAINT casos_unicos do UPDATE SET {}'. \ format(table_name, ','.join(col_names), ','.join(['%s' for i in col_names]), ','.join(['{0}=excluded.{0}'.format(j) for j in col_names])) logger.info("Formatando linhas e inserindo em {}".format( table_name)) for row in self.tabela[df_names].iterrows(): i = row[0] row = row[1] row[0] = None if isinstance(row[0], pd.tslib.NaTType) else date.fromordinal( row[0].to_datetime().toordinal()) # dt_notific row[1] = int(str(int(row[1]))[-2:]) # se_notific row[2] = int(self.ano) if pd.isnull(row[2]) else int(row[2]) # ano_notific row[3] = None if isinstance(row[3], pd.tslib.NaTType) else date.fromordinal( row[3].to_datetime().toordinal()) # dt_sin_pri row[4] = None if not row[4] else int(str(row[4])[-2:]) # se_sin_pri row[5] = None if isinstance(row[5], pd.tslib.NaTType) else date.fromordinal( row[5].to_datetime().toordinal()) # dt_digita row[7] = None if not row[7] else int(row[7]) # bairro_bairro_id row[8] = None if row[8] == '' else add_dv(int(row[8])) # municipio_geocodigo row[9] = int(row[9]) # nu_notific if row[10] is None: if default_cid is None: raise ValidationError(_("Existem nesse arquivo notificações " "que não incluem a coluna ID_AGRAVO.")) else: row[10] = default_cid row[11] = None if (isinstance(row[11], pd.tslib.NaTType) or row[11] is None) else date.fromordinal(row[11].to_datetime().toordinal()) # dt_nasc row[13] = None if not row[13] else int(row[13]) # nu_idade_n cursor.execute(insert_sql, row) if (i % 1000 == 0) and (i > 0): logger.info("{} linhas inseridas. Commitando mudanças " "no banco".format(i)) connection.commit() connection.commit() logger.info("Sinan {} inserido no banco".format(self.dbf))
def rand_date(start, end): """Returns a tuple of two randomly generated datetime objects between the start and end seed dates """ # convert dates to epoch representation start_ordinal = start.toordinal() end_ordinal = end.toordinal() # generate a random date between start and end rand_start_day = randint(start_ordinal, end_ordinal) rand_end_day = randint(start_ordinal, end_ordinal) # make sure end is after start while rand_end_day < rand_start_day: rand_end_day = randint(start_ordinal, end_ordinal) return (date.fromordinal(rand_start_day), date.fromordinal(rand_end_day))
def __init__(self, *cardTuple): # print(cardTuple) initDate = date.fromordinal(1) self.question = cardTuple[0] self.answer = cardTuple[1] self.EF = 2.5 if cardTuple[2] == None else cardTuple[2] self.repeat = 0 if cardTuple[3] == None else cardTuple[3] self.interval = 0 if cardTuple[4] == None else cardTuple[4] self.initDate = initDate if cardTuple[5] == None \ else date.fromordinal(cardTuple[5]) self.startDate = initDate if cardTuple[6] == None \ else date.fromordinal(cardTuple[6]) self.nextDate = initDate if cardTuple[7] == None \ else date.fromordinal(cardTuple[7])
def searchBacklog(self, which_shows=None): if self.amActive: sickrage.srLogger.debug("Backlog is still running, not starting it again") return self.amActive = True self.amPaused = False if which_shows: show_list = which_shows else: show_list = sickrage.srCore.SHOWLIST self._get_lastBacklog() curDate = date.today().toordinal() fromDate = date.fromordinal(1) if not which_shows and not ((curDate - self._lastBacklog) >= self.cycleTime): sickrage.srLogger.info( "Running limited backlog on missed episodes " + str( sickrage.srConfig.BACKLOG_DAYS) + " day(s) and older only") fromDate = date.today() - timedelta(days=sickrage.srConfig.BACKLOG_DAYS) # go through non air-by-date shows and see if they need any episodes for curShow in show_list: if curShow.paused: continue segments = self._get_segments(curShow, fromDate) for season, segment in segments.iteritems(): self.currentSearchInfo = {'title': curShow.name + " Season " + str(season)} backlog_queue_item = BacklogQueueItem(curShow, segment) sickrage.srCore.SEARCHQUEUE.add_item(backlog_queue_item) # @UndefinedVariable else: sickrage.srLogger.debug("Nothing needs to be downloaded for {show_name}, skipping".format(show_name=curShow.name)) # don't consider this an actual backlog search if we only did recent eps # or if we only did certain shows if fromDate == date.fromordinal(1) and not which_shows: self._set_lastBacklog(curDate) self.amActive = False self._resetPI()
def cargar_menu_dia(request, ordinal_dia): "Carga un menu para un dia determinado" dia = date.fromordinal(int(ordinal_dia)) menu_dia_form = MenuDiaForm() error = None if request.method == 'POST': nombre = request.POST['nombre'] contenido = request.POST['contenido'] if nombre and contenido: menu_dia = MenuDia() menu_dia.dia = dia menu_dia.nombre = nombre menu_dia.contenido = contenido menu_dia.save() return HttpResponseRedirect(request.GET['next']) else: menu_dia_form = MenuDiaForm(request.POST) error = "Che, faltan completar algunas cosas." dia_semana = DIAS_SEMANA[dia.weekday()] menues = MenuDia.objects.filter(dia=dia).order_by('nombre') return render_to_response('wozoapp/cargar_menu_dia.html', {'menu_dia_form': menu_dia_form, 'dia_ordinal': dia.toordinal(), 'dia': dia, 'dia_semana': dia_semana, 'menues': menues, 'user': request.user, 'root_url': root_url, 'actual_url': request.path, 'error': error})
def setUp(self): GaiaTestCase.setUp(self) self.phone = Phone(self.marionette) self.phone.launch() current_time = repr(time.time()).replace('.', '') self.phone_number_1 = '555%s' % current_time[-7:] self.phone_number_2 = '444%s' % current_time[-7:] self.yesterday_date = date.fromordinal(date.today().toordinal()-1) self.past_date_1 = date(2014, 12, 01) self.past_date_2 = date(2013, 12, 01) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_1)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_2)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_1, date=self.yesterday_date)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_1, date=self.past_date_1)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_2, date=self.past_date_1)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_2, date=self.past_date_1)) self.data_layer.insert_call_entry(MockCall(phone_number=self.phone_number_1, date=self.past_date_2))
def generate_event(self, event_num): e = Event() min_date = (date.today() + timedelta(days=-5)).toordinal() max_date = (date.today() + timedelta(days=5)).toordinal() e.start_date = random_day = date.fromordinal(random.randint(min_date, max_date)) e.end_date = e.start_date + timedelta(0, 60 * 60) # duration 60 minutes e.title = 'Event %d' % event_num e.descr = 'Description for event %d' % event_num e.lat = random.randint(24000, 26000)/1000.0 e.lon = random.randint(58000, 62000)/1000.0 ''' e.street_address = models.CharField(max_length=500) e.city = models.CharField(max_length=500) e.country = models.CharField(max_length=100) ''' e.org_name = 'Sample Organizer' e.org_email = '*****@*****.**' e.org_phone = '+358501234567' e.save() return
def run(self, args): super(QueueStatsCommand, self).run(args) days = int(args.days) + 1 self.load_app() models.start() today = date.today() day_objs = [] for day_num in range(days)[::-1]: day = date.fromordinal(today.toordinal() - day_num) day_objs.append(day) job_counts = {} for day in day_objs: if day_objs[0] == day: continue prev_day = day_objs[day_objs.index(day) - 1] jobs_sched = self.jobs_scheduled_between(prev_day, day).count() jobs_done = self.jobs_completed_between(prev_day, day).count() if jobs_sched == 0: percent = 0 else: percent = float(jobs_done) / float(jobs_sched) * 100 job_counts[day] = OrderedDict(scheduled=jobs_sched, completed=jobs_done, percent=percent, ) print "{day}: {sched: >4} scheduled, {done: >4} completed ({percent:.0f}%)".format( day=day, sched=jobs_sched, done=jobs_done, percent=percent, )
def fromordinal(cls, ordinal): """Return the week corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 starts the week with ordinal 1. """ if ordinal < 1: raise ValueError("ordinal must be >= 1") return super(Week, cls).__new__(cls, *(date.fromordinal((ordinal-1) * 7 + 1).isocalendar()[:2]))
def _calc_historical_200_day_sma(self,symbol): retArray = []; prArray = []; today = date.today() enddate = today.strftime("%Y%m%d") today_ordinal = date.toordinal(today) start_ordinal = today_ordinal - 380; startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d") #print startdate #print enddate retArray.append(symbol) prArray.append(symbol) xx = yahoostock.get_historical_prices(symbol,startdate,enddate) #print xx #print xx[1] for i in range (1,241): #print "%d" % (i) #print xx[i] x2 = xx[i]; prArray.append(x2[1]) for i in range (1,self.numSma+1): sma = 0.0 for mm in range (i,i+200): sma += float(prArray[mm]); sma = sma / 200.0 retArray.append(sma) return [retArray, prArray]
def random_date(): start_dt = date.today().replace(day=1, month=1, year=2012).toordinal() end_dt = date.today().replace(day=31, month=12, year=2042).toordinal() random_day = date.fromordinal(random.randint(start_dt, end_dt)) return (random_day)
def from_matlab(self, v): return date.fromordinal(int(v - 366))
import Perturb ######################################################################## ######################################################################## # Set cpus for ROMS: xcpu=3 ycpu=8 # Set cpus for CICE: icecpu=8 # Choose a predefined ROMS-application: app='arctic-20km' # Arctic-20km interval=10 start_date = datetime(2010,1,01,00) #end_date = datetime(2010,01,11,00) new_end = date.fromordinal(date.toordinal(start_date) +interval) end_date = datetime(new_end.year, new_end.month, new_end.day,00) Max_ens=10 run='Coupled_Results/Coupled_Pert' orig_folder='/global/work/sfr009/Coupled_Pert/tmproms/run/arctic-20km/' ice_folder='/global/work/sfr009/Coupled_Pert/tmproms/run/arctic-20km/cice/rundir/restart/' dest_folder='/global/work/sfr009/'+run+'/' obs_folder='/global/work/sfr009/OSISAF/' if os.path.isdir(dest_folder) is False: os.mkdir( dest_folder, 0755 ); print "Path is created"
'--user mdehghaniashkez --pwd Jazireie08 ' + \ '--motu http://nrt.cmems-du.eu/motu-web/Motu ' + \ '--service-id OCEANCOLOUR_GLO_CHL_L4_NRT_OBSERVATIONS_009_033-TDS ' + \ '--product-id dataset-oc-glo-chl-multi-l4-oi_4km_daily-rt-v02 ' + \ '--longitude-min 0.125 --longitude-max -0.125 ' + \ '--latitude-min -89.875 --latitude-max 89.875 --date-min "' c3 = '" --date-max "' c4 = '" --variable CHL --variable CHL_error --out-dir %s --out-name ' % cfgv.nrt_chl_raw #for index in range(startDay,endDay+1): index = startDay while index <= endDay: print('*************') print('Downloading: ' + str(yr * 1000 + index)) print('*************') tup = date.fromordinal(date(yr, 1, 1).toordinal() + index - 1) c2 = str(tup.year) + '-' + str(tup.month).zfill(2) + '-' + str( tup.day).zfill(2) c5 = cfgv.nrt_chl_prefix + str(yr) + str(index).zfill(3) + '.nc' command = c1 + c2 + c3 + c2 + c4 + c5 os.system(command) sleep(1) if raw_file_exists(cfgv.nrt_chl_raw, cfgv.nrt_chl_prefix, yr * 1000 + index, '.nc'): index = index + 1 else: print('Not Successful in downloading: ' + str(yr * 1000 + index)) #dml.updateChecklist(index, dl.daynToDate(index).year, dl.daynToDate(index).month, dl.daynToDate(index).day, 'NRT_CHL_Raw', 1)
def feriadomovel(str_ano, str_data): print('feriadomovel ano:' + str_ano) print('feriadomovel data:' + str_data) cferiado = "" X = 24 Y = 5 ANO = int(str_ano) A = ANO % 19 # print A B = ANO % 4 # print B C = ANO % 7 # print C D = (19 * A + X) % 30 # print D E = (2 * B + 4 * C + 6 * D + Y) % 7 # print E if ((D + E) > 9): DIA = D + E - 9 MES = 4 if DIA < 10: DIAATUAL = "0" + str(DIA) else: DIAATUAL = str(DIA) PASCOA = str(ANO) + "-0" + str(MES) + "-" + DIAATUAL if (str_data == PASCOA): cferiado = "Pascoa" DATA1 = date(ANO, MES, DIA) # O carnaval sera a subtracao de 47 dias da data da pascoa CARNAVAL = date.fromordinal(DATA1.toordinal() - 47) if (str_data == str(CARNAVAL)): cferiado = "Carnaval" # corpus christi ocorre 60 dias após o domingo de Páscoa CORPUSCRISTI = date.fromordinal(DATA1.toordinal() + 60) if (str_data == str(CORPUSCRISTI)): cferiado = "Corpus Christi" # A sexta-feira santa ocorre 2 dias antes do domingo de Páscoa SEXTAFEIRASANTA = date.fromordinal(DATA1.toordinal() - 2) if (str_data == str(SEXTAFEIRASANTA)): cferiado = "Sexta-Feira Santa" else: DIA = D + E + 22 MES = 3 if DIA < 10: DIAATUAL = "0" + str(DIA) else: DIAATUAL = str(DIA) PASCOA = str(ANO) + "-0" + str(MES) + "-" + DIAATUAL if (str_data == PASCOA): cferiado = "Pascoa" DATA1 = date(ANO, MES, DIA) CARNAVAL = date.fromordinal(DATA1.toordinal() - 47) if (str_data == str(CARNAVAL)): cferiado = "Carnaval" # corpus christi ocorre 60 dias após o domingo de Páscoa CORPUSCRISTI = date.fromordinal(DATA1.toordinal() + 60) if (str_data == str(CORPUSCRISTI)): cferiado = "Corpus Christi" # A sexta-feira santa ocorre 2 dias antes do domingo de Páscoa SEXTAFEIRASANTA = date.fromordinal(DATA1.toordinal() - 2) if (str_data == str(SEXTAFEIRASANTA)): cferiado = "Sexta-Feira Santa" return (cferiado)
def date_from_ordinal(ordinal): return date.fromordinal(ordinal + BASE_ORDINAL)
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as pl import os import functions as funct ### Sea Level Pressure SSP_file = '/Users/jmh2g09/Documents/PhD/Data/SSPressure/ERA_Interim_mean_sea_level_pressure.nc' # Load SSP data nc = Dataset(SSP_file, 'r') SSP_lat = nc.variables['latitude'][:] SSP_lon = nc.variables['longitude'][:] SSP_time = nc.variables['time'][:] / 24 + date.toordinal(date(1900, 1, 1))# Convert to days SSP_dates = [] for it in range(len(SSP_time)): SSP_dates.append(date.fromordinal(int(SSP_time[it]))) # SSP (Pa) SSP_data = nc.variables['msl'][:]# (time, lat, lon) nc.close() # Apply the GMT land mask nc = Dataset('/Users/jmh2g09/Documents/PhD/Data/Gridded/mask_full_05degree.nc', 'r') # Load the mask (ocean == 1) ocean_mask_05 = np.flipud(nc.variables['z'][:]) ocean_mask_05[ocean_mask_05 != 1] = np.NaN nc.close() SSP_data_anom_masked = np.full(np.shape(SSP_data), fill_value=np.NaN) for it in range(len(SSP_time)): SSP_data_anom_masked[it, :, :] = SSP_data[it, :, :] * ocean_mask_05
#!/usr/bin/env python3 """ Fetch a week of tweets Once a week go over the entire year to fill in possible gaps in the local database requires celery worker to be up and running but this script will actually be executed by cron """ import sys, os from datetime import datetime, timedelta, date sys.path.append(os.getcwd()) from crawlclima.tasks import pega_tweets from itertools import islice # Data inicial da captura today = date.fromordinal(date.today().toordinal()) week_ago = date.fromordinal(date.today().toordinal()) - timedelta(8) year_start = date(date.today().year, 1, 1) with open("municipios") as f: municipios = f.read().split('\n') municipios = list(filter(None, municipios)) def chunk(it, size): """ divide a long list into sizeable chuncks :param it: iterable :param size: chunk size :return:
def fromordinal(self, ordinal): """lunardate.fromordinal(ordinal) -> new lunardate object Returns corresponding lunardate object from Gregorian ordinal.""" return self.fromsolardate(date.fromordinal(ordinal))
def get_start_date(days_to_check): return date.fromordinal( max(date.today().toordinal() - (days_to_check - 1), 1)).strftime('%Y-%m-%d')
from datetime import date from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import pylab as pl import numpy as np start = datetime(2014, 1, 1) end = datetime(2014, 12, 31) quotesMSFT = quotes_historical_yaho_ochl('MSFT', start, end) quotesINTC = quotes_historical_yahoo_ochl('INTC', start, end) fields = ['date', 'open', 'close', 'high', 'low', 'volume'] #quotesdf = pd.DataFrame(quotes, columns = fields) #quotesdf = pd.DataFrame(quotes, index = range(1,len(quotes)+1),columns = fields) list1 = [] for i in range(0, len(quotesMSFT)): x = date.fromordinal(int(quotesMSFT[i][0])) y = datetime.strftime(x, '%Y-%m-%d') list1.append(y) #print list1 list2 = [] for i in range(0, len(quotesINTC)): x = date.fromordinal(int(quotesINTC[i][0])) y = datetime.strftime(x, '%Y-%m-%d') list2.append(y) quotesmsftdf = pd.DataFrame(quotesMSFT, index=list1, columns=fields) quotesmsftdf = quotesmsftdf.drop(['date'], axis=1) #print quotesdf quotesintcdf = pd.DataFrame(quotesINTC, index=list1, columns=fields) quotesintcdf = quotesintcdf.drop(['date'], axis=1) listtemp1 = [] for i in range(0, len(quotesmsftdf)):
t_data[cnt] = dates_data[cnt].toordinal() cnt += 1 sst_data[sst_data == fillValue] = np.nan sst_data[sst_data <= -2] = np.nan sst_data[sst_data >= 35] = np.nan lat_data = np.flipud(lat_data) # flip order of lat coords sst_data = sst_data[:, ::-1, :] T_data = len(t_data) LON = len(lon_data) LAT = len(lat_data) year_data = np.zeros(T_data) month_data = np.zeros(T_data) for mth in range(T_data): year_data[mth] = date.fromordinal(t_data[mth].astype(int)).year month_data[mth] = date.fromordinal(t_data[mth].astype(int)).month # Limit data to post-yearStart years_proxies = range(yearStart, yearEnd + 1) tt = (year_data >= yearStart) * (year_data <= yearEnd) sst_data = sst_data[tt] if sw_sig: sig_data = sig_data[tt] year_data = year_data[tt] month_data = month_data[tt] # Initialize empty dictionary of proxies T_proxies = len(years_proxies) missing = np.nan * np.zeros((T_proxies, LAT, LON)) proxy = {}
13314.5, 13345.5, 13376.5, 13406.5, 13437.5, 13467.5, 13498.5, 13529.5, 13558.5, 13588.5, 13618.5, 13649.5, 13679.5, 13710.5, 13741.5, 13771.5, 13802.5, 13832.5, 13863.5, 13894.5, 13924.5, 13954.5, 13984.5, 14015.5, 14045.5, 14076.5, 14107.5, 14137.5, 14168.5, 14198.5, 14229.5, 14260.5, 14289.5, 14319.5, 14349.5, 14380.5, 14410.5, 14441.5, 14472.5, 14502.5, 14533.5, 14563.5, 14594.5, 14625.5, 14654.5, 14684.5, 14714.5, 14745.5, 14775.5, 14806.5, 14837.5, 14867.5, 14898.5, 14928.5, 14959.5, 14990.5, 15019.5, 15049.5, 15079.5, 15110.5, 15140.5, 15171.5, 15202.5, 15232.5, 15263.5, 15293.5, 15324.5, 15355.5, 15386.5, 15415.5, 15446.5, 15476.5 ] base = date(1970, 01, 01) arcMap = {} index = 1 for aBandtime in arcBandTime: d = date.fromordinal(int(base.toordinal() + aBandtime)) arcMap[d.strftime('%Y-%m')] = str(index) index += 1 ############################################################################ def ratio490Threshold(region): if region in ratio490Threshholds: return ratio490Threshholds.get(region) else: return '0.65' # default def arcAuxdata(region, year, month): if region in arcFileIdByRegion:
# -*- coding: utf-8 -*- from matplotlib.finance import quotes_historical_yahoo_ochl from datetime import date import pandas as pd today = date.today() start = (today.year - 2, today.month, today.day) quotesMS = quotes_historical_yahoo_ochl('MSFT', start, today) attributes = ['date', 'open', 'close', 'high', 'low', 'volume'] quotesdfMS = pd.DataFrame(quotesMS, columns=attributes) list = [] for i in range(0, len(quotesMS)): x = date.fromordinal(int(quotesMS[i][0])) y = date.strftime(x, '%y/%m/%d') list.append(y) quotesdfMS.index = list quotesdfMS = quotesdfMS.drop(['date'], axis=1) list = [] quotesdfMS15 = quotesdfMS['15/01/01':'15/12/31'] for i in range(0, len(quotesdfMS15)): list.append(int(quotesdfMS15.index[i][3:5])) # get month just like '02' quotesdfMS15['month'] = list print(quotesdfMS15.groupby('month').mean().close)
def acaoMenu(acaoParaRealizar): if acaoParaRealizar == "1": #Agendar Vacina listaUsada = listarVacina() #Função para listar as vacinas do usuário agendarTemp = int( input( "\n Por favor, selecione o número correspondente à vacina que você deseja agendar: " )) - 1 #Determina a vacina que será agendada while listaRepeticaoVacina[ agendarTemp] == 0: #Caso a repetição da vacina escolhida seja = 0 agendarTemp = int( input( "Você já tomou todas as doses desta vacina. Por favor, selecione o número correspondente à vacina que você deseja agendar: " )) - 1 if listaRepeticaoVacina[ agendarTemp] > 0: #Se ainda tiver aplicações da vacina pendentes disponibilidade = random.randrange( 3, 25 ) #Determina aleatóriamente uma data disponível para aplicação dos postos de saúde (através da biblioteca random) agendarDia = int( input( "\nOs postos de saúde terão disponibilidade para aplicação desta vacina em " + str(disponibilidade) + " dias. \nDaqui a quantos dias você deseja agendar a aplicação da mesma? (O número deve ser maior ou igual a data de disponibilidade e menor que 1 ano): " )) #Pede o dia desejado para aplicação while ( agendarDia < disponibilidade or agendarDia > 365 ): #Verifica se a data está disponível e está dentro do limite de um ano agendarDia = int( input( "\nA data precisa ser maior ou igual à disponibilidade e estar dentro do período de um ano. \nOs postos de saúde terão disponibilidade para aplicação desta vacina em " + str(disponibilidade) + " dias. \nDaqui a quantos dias você deseja agendar a aplicação da mesma? (O número deve ser maior ou igual a data de disponibilidade e menor que 1 ano): " )) numeroDiaAtualtemp = diaAtual.toordinal( ) #Variável que armazena o dia atual em ordinal. (Através da biblioteca date) diaAgendado = agendarDia + numeroDiaAtualtemp #Calcula o dia para aplicação (ordinal) diaAgendado = date.fromordinal( diaAgendado) #Determina o dia de aplicação (não ordinal) diaAgendado.strftime( "%d/%m/%Y" ) #Transforma em string a data de aplicação (No formato Dia/Mês/Ano) listaVacinasAgendadas.append( "Vacina : " + str(listaUsada[agendarTemp]) + " Dia: " + str(diaAgendado) ) #Adiciona a vacina e a data agendada na lista de agendamentos repeticaoTemp = listaRepeticaoVacina[ agendarTemp] #Armazena a(s) dose(s) da vacina escolhida repeticaoTemp -= 1 #Diminui uma dose da vacina escolhida listaRepeticaoVacina.pop( agendarTemp) #Retira a dose da lista (por posição) listaRepeticaoVacina.insert( agendarTemp, repeticaoTemp ) #Adiciona a dose ajustada na lista (na mesma posição) input("A vacina " + str(listaUsada[agendarTemp]) + " está agendada para o dia " + str(diaAgendado) + ". Pressione ENTER para retornar ao menu." ) #Mensagem de confirmação e retorno ao menu elif acaoParaRealizar == "2": #Vacinas Agendadas for i in listaVacinasAgendadas: #Printa as vacinas agendadas de acordo com a lista print(i) input("Pressione ENTER para voltar ao menu: ") #Retornar ao menu acaoParaRealizar = "0" elif acaoParaRealizar == "3": #Histórico de vacinação for i in listaVacinasTomadas: #Printa as vacinas já aplicadas de acordo com a lista print(i) input("Pressione ENTER para retornar ao menu.") #Retornar ao menu elif acaoParaRealizar == "4": #Aplicação de vacina não agendada listaUsada = listarVacina() #Printa as vacinas do usuário vacinaAplicada = int( input("Informe o número correspondente a vacina aplicada: ") ) - 1 #Pede o número correspondente a vacina aplicada while listaRepeticaoVacina[ vacinaAplicada] <= 0: #Verifica se a vacina já não estava aplicada anteriormente ou se existe um agendamento prévio vacinaAplicada = int( input( "Esta vacina já foi aplicada, ou existe um agendamento pendente. Informe o número correspondente a vacina aplicada: " )) - 1 diaTomado = int(input("Há quantos dias a vacina foi aplicada? : ") ) #Pede a data de aplicação da vacina while diaTomado < 0: #Verifica se a aplicação foi retroativa diaTomado = int( input( "(Insira um número maior ou igual à zero.) Há quantos dias a vacina foi aplicada? : " )) numeroDiaAtualtemp = diaAtual.toordinal( ) #Armazena a data atual do sistema diaTomado = numeroDiaAtualtemp - diaTomado #Calcula o dia de aplicação diaTomado = date.fromordinal( diaTomado) #Transforma o dia de aplicação em não ordinal repeticaoTemp = listaRepeticaoVacina[ vacinaAplicada] #Armazena a(s) dose(s) da vacina escolhida repeticaoTemp -= 1 #Diminui uma dose da vacina aplicada listaRepeticaoVacina.pop( vacinaAplicada) #Retira a dose da lista (por posição) listaRepeticaoVacina.insert( vacinaAplicada, repeticaoTemp ) #Adiciona a dose ajustada na lista (na mesma posição) diaTomado.strftime( "%d/%m/%Y") #Transforma a data de aplicação em string listaVacinasTomadas.append( "Vacina : " + str(listaUsada[vacinaAplicada]) + " Dia: " + str(diaTomado) ) #Adiciona a data de aplicação na lista de vacinas tomadas elif acaoParaRealizar == "5": #Informações sobre as vacinas print( "Informações sobre as vacinas fornecidas pelo Ministério da Saúde: " ) for i in listaInformacoesVacina: #Printa as informações sobre as vacinas listadas print(i) input("\n Pressione ENTER para voltar ao menu.") #Retornar ao menu elif acaoParaRealizar == "6": #Perfil do usuário dataTemp = listaNascimento[ identificadorDoUsuario] #Armazena a data de nascimento do usuário diaTemp = dataTemp[0:2] #Armazena o dia de nascimento mesTemp = dataTemp[2:4] #Armazena o mês de nascimento anoTemp = dataTemp[4:9] #Armazena o ano de nascimento dataEscrita = str(diaTemp) + "/" + str(mesTemp) + "/" + str( anoTemp ) #Adiciona os caracteres especiais relacionados a data de nascimento print("\nNome do Usuário: ", nome, ".\nCPF: ", listaLogin[identificadorDoUsuario], "\nData de nascimento: ", dataEscrita, "\nCidade: ", listaLocalidade[identificadorDoUsuario] ) #Lista os dados do usuário input("\nPressione 'ENTER' para voltar ao menu.") #Retornar ao menu elif acaoParaRealizar == "7": #Informações sobre o PyVacina print( "\nO ditado popular “melhor prevenir do que remediar” se aplica perfeitamente à vacinação. Muitas doenças comuns \nno Brasil e no mundo deixaram de ser um problema de saúde pública por causa da vacinação massiva da população.\nPoliomielite, sarampo, rubéola, tétano e coqueluche são só alguns exemplos de doenças comuns no passado e que \nas novas gerações só ouvem falar em histórias. O resultado da vacinação não se resume a evitar doença. \nVacinas salvam vidas." ) print( "\nO PyVacina é um aplicativo que auxilia no monitoramento de suas vacinas. \nNele é possível ver as suas vacinas aplicadas e agendar novas aplicações. \nO PyVacina está em sua versão beta " + str(versao) + "\nDesenvolvedores: Bryan Yassunori Tanaka e Leonardo Mafra Salin." ) input("\nPressione 'ENTER' para voltar ao menu.") #(1) acaoParaRealizar = "0" elif acaoParaRealizar == "8": #Deslogar print( "\n\n\nDeslogando...\n\n\n\n==================================================================================================================" ) acaoParaRealizar = 0 return 0 elif acaoParaRealizar == "9": #Fechar o programa print("Finalizando...") acaoParaRealizar = 0 else: acaoParaRealizar = "0"
| | _ __ __ _ | |_ __ _ | \ / | | | | | | (___ | | | '__| / _` | | __| / _` | | |\/| | | | | | \___ \ | | | | | (_| | | |_ | (_| | | | | | | |__| | ____) | |_| |_| \__,_| \__| \__,_| |_| |_| \____/ |_____/ powered on PYTHON!!! developer: N5669203 ''') #Aqui tenho um dicionario com os meses do ano para buscar a pagina do MOS pela data do dia anterior mes = {0:'lixo', 1:'JAN', 2:'FEB', 3:'MAR', 4:'APR', 5:'MAY', 6:'JUN', 7:'JUL', 8:'AUG', 9:'SEP', 10:'OCT', 11:'NOV', 12:'DEC'} endereco_MOS = ['http://vqr.virtua.com.br/get_vqr_status.php?data=', '10-OCT-17', '&switch_id=114&switch_name=JPADTCDPI-01&schema_version=v766'] hoje = date.today() diaTratativa = date.fromordinal(hoje.toordinal()- 1) anoTratativa = str(diaTratativa.year) #print(str(diaTratativa.day) + '-' + str(mes[diaTratativa.month]) + '-' + anoTratativa[2:4]) #Aqui eu monto a string para buscar a pagina #Abaixo temos o endereco ja pronto para fazer a consulta, mas para testes vou usar o endereço local #consultaMOS = endereco_MOS[0] + str(diaTratativa.day) + '-' + str(mes[diaTratativa.month]) + '-' + anoTratativa[2:4] + endereco_MOS[2] #Aqui seto o endereco local. para usar a web usar o request paginaMOS = open('html_teste\VQR - Call Scores.html') paginaSoup = bs4.BeautifulSoup(paginaMOS.read(), "html.parser") #caso de erro no linux, tirar a referencia ao html5lib
def _ep_data(self, ep_obj): """ Creates an elementTree XML structure for a MediaBrowser style episode.xml and returns the resulting data object. show_obj: a TVShow instance to create the NFO for """ eps_to_write = [ep_obj] + ep_obj.relatedEps persons_dict = {'Director': [], 'GuestStar': [], 'Writer': []} indexer_lang = ep_obj.show.lang try: lINDEXER_API_PARMS = sickrage.srCore.INDEXER_API( ep_obj.show.indexer).api_params.copy() lINDEXER_API_PARMS[b'actors'] = True if indexer_lang and not indexer_lang == sickrage.srConfig.INDEXER_DEFAULT_LANGUAGE: lINDEXER_API_PARMS[b'language'] = indexer_lang if ep_obj.show.dvdorder != 0: lINDEXER_API_PARMS[b'dvdorder'] = True t = sickrage.srCore.INDEXER_API( ep_obj.show.indexer).indexer(**lINDEXER_API_PARMS) myShow = t[ep_obj.show.indexerid] except indexer_shownotfound as e: raise ShowNotFoundException(e.message) except indexer_error as e: sickrage.srLogger.error( "Unable to connect to " + sickrage.srCore.INDEXER_API(ep_obj.show.indexer).name + " while creating meta files - skipping - {}".format(e.message)) return False rootNode = Element("Item") # write an MediaBrowser XML containing info for all matching episodes for curEpToWrite in eps_to_write: try: myEp = myShow[curEpToWrite.season][curEpToWrite.episode] except (indexer_episodenotfound, indexer_seasonnotfound): sickrage.srLogger.info( "Unable to find episode %dx%d on %s... has it been removed? Should I delete from db?" % (curEpToWrite.season, curEpToWrite.episode(ep_obj.show.indexer).name)) return None if curEpToWrite == ep_obj: # root (or single) episode # default to today's date for specials if firstaired is not set if ep_obj.season == 0 and not getattr(myEp, 'firstaired', None): myEp[b'firstaired'] = str(date.fromordinal(1)) if not (getattr(myEp, 'episodename', None) and getattr(myEp, 'firstaired', None)): return None episode = rootNode if curEpToWrite.name: EpisodeName = SubElement(episode, "EpisodeName") EpisodeName.text = curEpToWrite.name EpisodeNumber = SubElement(episode, "EpisodeNumber") EpisodeNumber.text = str(ep_obj.episode) if ep_obj.relatedEps: EpisodeNumberEnd = SubElement(episode, "EpisodeNumberEnd") EpisodeNumberEnd.text = str(curEpToWrite.episode) SeasonNumber = SubElement(episode, "SeasonNumber") SeasonNumber.text = str(curEpToWrite.season) if not ep_obj.relatedEps and getattr(myEp, 'absolute_number', None): absolute_number = SubElement(episode, "absolute_number") absolute_number.text = str(myEp[b'absolute_number']) if curEpToWrite.airdate != date.fromordinal(1): FirstAired = SubElement(episode, "FirstAired") FirstAired.text = str(curEpToWrite.airdate) MetadataType = SubElement(episode, "Type") MetadataType.text = "Episode" if curEpToWrite.description: Overview = SubElement(episode, "Overview") Overview.text = curEpToWrite.description if not ep_obj.relatedEps: if getattr(myEp, 'rating', None): Rating = SubElement(episode, "Rating") Rating.text = myEp[b'rating'] if getattr(myShow, 'imdb_id', None): IMDB_ID = SubElement(episode, "IMDB_ID") IMDB_ID.text = myShow[b'imdb_id'] IMDB = SubElement(episode, "IMDB") IMDB.text = myShow[b'imdb_id'] IMDbId = SubElement(episode, "IMDbId") IMDbId.text = myShow[b'imdb_id'] indexerid = SubElement(episode, "id") indexerid.text = str(curEpToWrite.indexerid) # fill in Persons section with collected directors, guest starts and writers Persons = SubElement(episode, "Persons") for person_type, names in persons_dict.iteritems(): # remove doubles names = list(set(names)) for cur_name in names: Person = SubElement(Persons, "Person") cur_person_name = SubElement(Person, "Name") cur_person_name.text = cur_name cur_person_type = SubElement(Person, "Type") cur_person_type.text = person_type if getattr(myShow, '_actors', None): for actor in myShow[b'_actors']: if not ('name' in actor and actor[b'name'].strip()): continue cur_actor = SubElement(Persons, "Person") cur_actor_name = SubElement(cur_actor, "Name") cur_actor_name.text = actor[b'name'].strip() cur_actor_type = SubElement(cur_actor, "Type") cur_actor_type.text = "Actor" if 'role' in actor and actor[b'role'].strip(): cur_actor_role = SubElement(cur_actor, "Role") cur_actor_role.text = actor[b'role'].strip() Language = SubElement(episode, "Language") try: Language.text = myEp[b'language'] except Exception: Language.text = sickrage.srConfig.INDEXER_DEFAULT_LANGUAGE # tvrage api doesn't provide language so we must assume a value here thumb = SubElement(episode, "filename") # TODO: See what this is needed for.. if its still needed # just write this to the NFO regardless of whether it actually exists or not # note: renaming files after nfo generation will break this, tough luck thumb_text = self.get_episode_thumb_path(ep_obj) if thumb_text: thumb.text = thumb_text else: # append data from (if any) related episodes if curEpToWrite.episode: if not EpisodeNumberEnd.text: EpisodeNumberEnd.text = curEpToWrite.episode else: EpisodeNumberEnd.text = EpisodeNumberEnd.text + ", " + curEpToWrite.episode if curEpToWrite.name: if not EpisodeName.text: EpisodeName.text = curEpToWrite.name else: EpisodeName.text = EpisodeName.text + ", " + curEpToWrite.name if curEpToWrite.description: if not Overview.text: Overview.text = curEpToWrite.description else: Overview.text = Overview.text + "\r" + curEpToWrite.description # collect all directors, guest stars and writers if getattr(myEp, 'director', None): persons_dict[b'Director'] += [ x.strip() for x in myEp[b'director'].split('|') if x.strip() ] if getattr(myEp, 'gueststars', None): persons_dict[b'GuestStar'] += [ x.strip() for x in myEp[b'gueststars'].split('|') if x.strip() ] if getattr(myEp, 'writer', None): persons_dict[b'Writer'] += [ x.strip() for x in myEp[b'writer'].split('|') if x.strip() ] indentXML(rootNode) data = ElementTree(rootNode) return data
def _get_random_day(self): return date.fromordinal(random.randint(self.start_date, self.end_date))
pas_fut = input("Esciba solo \'p\'o\'f\'según su opción: ") Dia1 = date(1, 1, 1) HOY = int((today - Dia1).days) + 1 #SE ESTABLECE EL ORDINAL DE LA FECHA ACTUAL Dia_ult = date(9999, 12, 31) fut_hoy = int( (Dia_ult - today).days) #SE ESTABLECE LO QUE FALTA PARA EL ULTIMO DIA if pas_fut == ("p"): while num > HOY: print( "La cantidad introducida es superior al numero de dias transcurridos, el tope es de", HOY - 1, "dias") num = OKI(input("Prueba con otro número: ")) dist = HOY - num dateo = date.fromordinal(dist) #RESUMIR date_spl = str(dateo).split("-") mes_nom = meses(date_spl) week_day = (dateo).weekday() dia_semana = semana(week_day) print("\nHace", num, "días era", dia_semana, date_spl[2], "de", mes_nom, "de", date_spl[0]) if pas_fut == ("f"): while num > fut_hoy: print( "La cantidad introducida es superior al numero de dias restantes, el tope es de", fut_hoy, "dias") num = OKI(input("Prueba con otro número: ")) dist = HOY + num dateo = date.fromordinal(dist) #RESUMIR date_spl = str(dateo).split("-")
from datetime import date print("1. Saber data daqui a x dias") print("2. Saber data há x dias") dia = date.today() escolha = int(input("Escolha uma opção: ")) if escolha == 1: print("") x = int(input("Valor: ")) futuro = date.fromordinal(dia.toordinal() + x) print("Data requerida:", futuro) elif escolha == 2: print("") x = int(input("Valor: ")) passado = date.fromordinal(dia.toordinal() - x) print("Data requerida:", passado) else: print("Valor inválido!")
if my_bday < today: my_bday = my_bday.replace(year=today.year + 1) my_bday # In[61]: timeToBday = abs(my_bday - today) timeToBday.days # In[62]: #ExampleWorkingWithDays from datetime import date d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 d # In[99]: d = date.fromordinal(736948) # 736965th day after 1. 1. 0001 d # In[100]: t = d.timetuple() # In[101]: for i in t: print(i)
def date_ordinal(match, other=None): data = {k: int(v) for k, v in match.groupdict().items() if v} days = (date_(data.get('year', 1), 1, 1) - date_(1, 1, 1)).days return date_.fromordinal(days + data.get('day', 0))
def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input data and the format string.""" global _locale_cache global _regex_cache locale_time = _locale_cache.locale_time # If the language changes, caches are invalidated, so clear them if locale_time.lang != _getlang(): _locale_cache = TimeRE() _regex_cache.clear() format_regex = _regex_cache.get(format) if not format_regex: # Limit regex cache size to prevent major bloating of the module; # The value 5 is arbitrary if len(_regex_cache) > 5: _regex_cache.clear() format_regex = _locale_cache.compile(format) _regex_cache[format] = format_regex found = format_regex.match(data_string) if not found: raise ValueError("time data did not match format: data=%s fmt=%s" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = 1900 month = day = 1 hour = minute = second = 0 tz = -1 week_of_year = -1 week_of_year_start = -1 # weekday and julian defaulted to -1 so as to signal need to calculate values weekday = julian = -1 found_dict = found.groupdict() for group_key in found_dict.iterkeys(): if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = _insensitiveindex(locale_time.f_month, found_dict['B']) elif group_key == 'b': month = _insensitiveindex(locale_time.a_month, found_dict['b']) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0].lower()): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1].lower(): # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'A': weekday = _insensitiveindex(locale_time.f_weekday, found_dict['A']) elif group_key == 'a': weekday = _insensitiveindex(locale_time.a_weekday, found_dict['a']) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': # U starts week on Sunday week_of_year_start = 6 else: # W starts week on Monday week_of_year_start = 0 elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() if found_zone in ("utc", "gmt"): tz = 0 elif time.tzname[0] == time.tzname[1] and \ time.daylight: continue #Deals with bad locale setup where timezone info is # the same; first found on FreeBSD 4.4. elif locale_time.timezone[2].lower() == found_zone: tz = 0 elif time.daylight and \ locale_time.timezone[3].lower() == found_zone: tz = 1 # If we know the week of the year and what day of that week, we can figure # out the Julian day of the year # Calculations below assume 0 is a Monday if julian == -1 and week_of_year != -1 and weekday != -1: # Calculate how many days in week 0 first_weekday = datetime_date(year, 1, 1).weekday() preceeding_days = 7 - first_weekday if preceeding_days == 7: preceeding_days = 0 # Adjust for U directive so that calculations are not dependent on # directive used to figure out week of year if weekday == 6 and week_of_year_start == 6: week_of_year -= 1 # If a year starts and ends on a Monday but a week is specified to # start on a Sunday we need to up the week to counter-balance the fact # that with %W that first Monday starts week 1 while with %U that is # week 0 and thus shifts everything by a week if weekday == 0 and first_weekday == 0 and week_of_year_start == 6: week_of_year += 1 # If in week 0, then just figure out how many days from Jan 1 to day of # week specified, else calculate by multiplying week of year by 7, # adding in days in week 0, and the number of days from Monday to the # day of the week if week_of_year == 0: julian = 1 + weekday - first_weekday else: days_to_week = preceeding_days + (7 * (week_of_year - 1)) julian = 1 + days_to_week + weekday # Cannot pre-calculate datetime_date() since can change in Julian #calculation and thus could have different value for the day of the week #calculation if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will #be accurate datetime_result = datetime_date.fromordinal( (julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday == -1: weekday = datetime_date(year, month, day).weekday() return time.struct_time( (year, month, day, hour, minute, second, weekday, julian, tz))
import allure import os import string from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from datetime import date import logging d = date.fromordinal(730920) now = d.strftime("%d-%m-%Y") path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) screen_dir = os.path.join(path, "screenshot", str(now)) def screen_path(): global screen_dir if not os.path.exists(screen_dir): os.makedirs(screen_dir) os.chmod(screen_dir, 0o755) return screen_dir def remove_special_characters(text): # text = text.translate(str.maketrans('', '', string.punctuation)) text = text.translate(str.maketrans('', '', '\ / : * ? " < > |')) return text
def days_between(start, stop): today = date(*start) stop = date(*stop) while today < stop: yield "http://jtwolohan.com/evilblog/" + today.strftime("%m-%d-%Y") today = date.fromordinal(today.toordinal() + 1)
def dtferiadomovel(cnomeferiado): cferiadodt = "" X = 24 Y = 5 ANO = datetime.date.today().year A = ANO % 19 # print A B = ANO % 4 # print B C = ANO % 7 # print C D = (19 * A + X) % 30 # print D E = (2 * B + 4 * C + 6 * D + Y) % 7 # print E if ((D + E) > 9): DIA = D + E - 9 MES = 4 if DIA < 10: DIAATUAL = "0" + str(DIA) else: DIAATUAL = str(DIA) PASCOA = str(ANO) + "-0" + str(MES) + "-" + DIAATUAL if (cnomeferiado == "pascoa"): cferiadodt = PASCOA DATA1 = date(ANO, MES, DIA) # O carnaval sera a subtracao de 47 dias da data da pascoa CARNAVAL = date.fromordinal(DATA1.toordinal() - 47) if (cnomeferiado == "carnaval"): cferiadodt = str(CARNAVAL) # corpus christi ocorre 60 dias após o domingo de Páscoa CORPUSCRISTI = date.fromordinal(DATA1.toordinal() + 60) if (cnomeferiado) == "corpus-christi": cferiadodt = str(CORPUSCRISTI) if (cnomeferiado) == "corpus christi": cferiadodt = str(CORPUSCRISTI) # A sexta-feira santa ocorre 2 dias antes do domingo de Páscoa SEXTAFEIRASANTA = date.fromordinal(DATA1.toordinal() - 2) if (cnomeferiado == "sexta-feira santa"): cferiadodt = str(SEXTAFEIRASANTA) if (cnomeferiado == "sexta-feira-santa"): cferiadodt = str(SEXTAFEIRASANTA) else: DIA = D + E + 22 MES = 3 if DIA < 10: DIAATUAL = "0" + str(DIA) else: DIAATUAL = str(DIA) PASCOA = str(ANO) + "-0" + str(MES) + "-" + DIAATUAL if (cnomeferiado == "pascoa"): cferiadodt = str(DIAATUAL) DATA1 = date(ANO, MES, DIA) CARNAVAL = date.fromordinal(DATA1.toordinal() - 47) if (cnomeferiado == "carnaval"): cferiadodt = str(CARNAVAL) # corpus christi ocorre 60 dias após o domingo de Páscoa CORPUSCRISTI = date.fromordinal(DATA1.toordinal() + 60) if (cnomeferiado) == "corpus-christi": cferiadodt = str(CORPUSCRISTI) if (cnomeferiado) == "Corpus christi": cferiadodt = str(CORPUSCRISTI) if (cnomeferiado) == "corpus christi": cferiadodt = str(CORPUSCRISTI) if (cnomeferiado) == "Corpus Christi": cferiadodt = str(CORPUSCRISTI) # A sexta-feira santa ocorre 2 dias antes do domingo de Páscoa SEXTAFEIRASANTA = date.fromordinal(DATA1.toordinal() - 2) if (cnomeferiado == "sexta-feira santa"): cferiadodt = str(SEXTAFEIRASANTA) if (cnomeferiado == "sexta-feira-santa"): cferiadodt = str(SEXTAFEIRASANTA) return (cferiadodt)
def read_date(data, writer_schema=None, reader_schema=None): return date.fromordinal(data + DAYS_SHIFT)
def ordinalToDate(ordinal): return date.fromordinal(ordinal) + datetime.timedelta(days=ordinal % 1) - datetime.timedelta(days=366)
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.""" for index, arg in enumerate([data_string, format]): if not isinstance(arg, str): msg = "strptime() argument {} must be str, not {}" raise TypeError(msg.format(index, type(arg))) global _TimeRE_cache, _regex_cache with _cache_lock: if _getlang() != _TimeRE_cache.locale_time.lang: _TimeRE_cache = TimeRE() _regex_cache.clear() if len(_regex_cache) > _CACHE_MAX_SIZE: _regex_cache.clear() locale_time = _TimeRE_cache.locale_time format_regex = _regex_cache.get(format) if not format_regex: try: format_regex = _TimeRE_cache.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" del err raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format)) from None # IndexError only occurs when the format string is "%" except IndexError: raise ValueError("stray %% in format '%s'" % format) from None _regex_cache[format] = format_regex found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = None month = day = 1 hour = minute = second = fraction = 0 tz = -1 tzoffset = None # Default to -1 to signify that values not known; not critical to have, # though week_of_year = -1 week_of_year_start = -1 # weekday and julian defaulted to -1 so as to signal need to calculate # values weekday = julian = -1 found_dict = found.groupdict() for group_key in found_dict.keys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives # U, W # worthless without day of the week if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = locale_time.f_month.index(found_dict['B'].lower()) elif group_key == 'b': month = locale_time.a_month.index(found_dict['b'].lower()) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0]): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1]: # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'f': s = found_dict['f'] # Pad to always return microseconds. s += "0" * (6 - len(s)) fraction = int(s) elif group_key == 'A': weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif group_key == 'a': weekday = locale_time.a_weekday.index(found_dict['a'].lower()) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': # U starts week on Sunday. week_of_year_start = 6 else: # W starts week on Monday. week_of_year_start = 0 elif group_key == 'z': z = found_dict['z'] tzoffset = int(z[1:3]) * 60 + int(z[3:5]) if z.startswith("-"): tzoffset = -tzoffset elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() for value, tz_values in enumerate(locale_time.timezone): if found_zone in tz_values: # Deal with bad locale setup where timezone names are the # same and yet time.daylight is true; too ambiguous to # be able to tell what timezone has daylight savings if (time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ("utc", "gmt")): break else: tz = value break leap_year_fix = False if year is None and month == 2 and day == 29: year = 1904 # 1904 is first leap year of 20th century leap_year_fix = True elif year is None: year = 1900 # If we know the week of the year and what day of that week, we can figure # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: week_starts_Mon = True if week_of_year_start == 0 else False julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian # calculation and thus could have different value for the day of the week # calculation. if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will # be accurate. datetime_result = datetime_date.fromordinal( (julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday == -1: weekday = datetime_date(year, month, day).weekday() # Add timezone info tzname = found_dict.get("Z") if tzoffset is not None: gmtoff = tzoffset * 60 else: gmtoff = None if leap_year_fix: # the caller didn't supply a year but asked for Feb 29th. We couldn't # use the default of 1900 for computations. We set it back to ensure # that February 29th is smaller than March 1st. year = 1900 return (year, month, day, hour, minute, second, weekday, julian, tz, tzname, gmtoff), fraction
FUNCIONARIO += "(%d, %d,'%d-%d-%d','%s');\n\n" % ( 30, r(1500, 8000), r(1935, 2002), r(1, 12), r(1, 28), gerar_nome_IBGE(sexo=['F', 'M'][r(0, 1)], composto=[True, False][r(0, 1)], femininos=femininos, masculinos=masculinos)) RESERVA = """insert into RESERVA(cod_RESERVA, cod_func, cod_hosp, num, dt_prev_entrada, dt_prev_saida) values """ HOSPEDAGEM = """insert into HOSPEDAGEM(cod_hospeda, cod_func, cod_hosp, num, dt_entrada, dt_saida) values """ GERAR_DATA = lambda x: date.fromordinal(x.toordinal() + r(1, 40)).isoformat() for i in range(1, 1000): dataR = date(r(2018, 2019), r(1, 12), r(1, 28)) dataH = date(r(2018, 2019), r(1, 12), r(1, 28)) if r(0, 1): cod_hosp = r(1, 500) ent = dataR.isoformat() sai = GERAR_DATA(dataR) num = r(1, 45) RESERVA += f"({i}, {r(1, 30)}, {cod_hosp}, {num}, '{ent}', '{sai}'),\n" HOSPEDAGEM += f"({i}, {r(1, 30)}, {cod_hosp}, {num}, '{ent}', '{sai}'),\n" else: RESERVA += f"({i}, {r(1, 30)}, {r(1, 500)}, {r(1, 45)}, '{dataR.isoformat()}', '{GERAR_DATA(dataR)}'),\n" HOSPEDAGEM += f"({i}, {r(1, 30)}, {r(1, 500)}, {r(1, 45)}, '{dataH.isoformat()}', '{GERAR_DATA(dataH)}'),\n" dataR = date(r(2018, 2019), r(1, 12), r(1, 28))