def get_current_date_position(work_date, frequency): frequency_id = frequency.identifier if frequency_id=='FREQ_DAILY': return 1 elif frequency_id=='FREQ_WEEKLY': week_day = work_date.isoweekday() return (week_day + 2) if week_day<=5 else (week_day - 5) elif frequency_id=='FREQ_MONTHLY': return work_date.day elif frequency_id=='FREQ_QUARTERLY': current_quarter = ((work_date.month-1)/3) + 1 days = 0 for c_month in range((current_quarter * 3) + 1, work_date.month + 1): if c_month==work_date.month: days += work_date.day else: days += monthrange(work_date.year, c_month) return days elif frequency_id=='FREQ_SEMESTERLY': current_quarter = ((work_date.month-1)/6) + 1 days = 0 for c_month in range((current_quarter * 6) + 1, work_date.month + 1): if c_month==work_date.month: days += work_date.day else: days += monthrange(work_date.year, c_month) return days elif frequency_id=='FREQ_ANNUALLY': return work_date.timetuple().tm_yday
def _compute_board_amount(self, sequence, residual_amount, amount_to_depr, undone_dotation_number, posted_depreciation_line_ids, total_days, depreciation_date): amount = 0 if sequence == undone_dotation_number: amount = residual_amount else: if self.method == 'linear': amount = amount_to_depr / (undone_dotation_number - len(posted_depreciation_line_ids)) if self.prorata: amount = amount_to_depr / self.method_number if sequence == 1: if self.method_period % 12 != 0: date = datetime.strptime(self.date, '%Y-%m-%d') month_days = calendar.monthrange(date.year, date.month)[1] days = month_days - date.day + 1 amount = (amount_to_depr / self.method_number) / month_days * days else: days = (self.company_id.compute_fiscalyear_dates(depreciation_date)['date_to'] - depreciation_date).days + 1 amount = (amount_to_depr / self.method_number) / total_days * days elif self.method == 'degressive': amount = residual_amount * self.method_progress_factor if self.prorata: if sequence == 1: if self.method_period % 12 != 0: date = datetime.strptime(self.date, '%Y-%m-%d') month_days = calendar.monthrange(date.year, date.month)[1] days = month_days - date.day + 1 amount = (residual_amount * self.method_progress_factor) / month_days * days else: days = (self.company_id.compute_fiscalyear_dates(depreciation_date)['date_to'] - depreciation_date).days + 1 amount = (residual_amount * self.method_progress_factor) / total_days * days return amount
def one_month_before(date): ''' Returns one month before. Accepts a date or datetime. Returns a datetime. >>> one_month_before(date(2012, 06, 01)) datetime.datetime(2012, 5, 1, 0, 0) >>> one_month_before(date(2012, 03, 30)) datetime.datetime(2012, 2, 29, 0, 0) >>> one_month_before(date(2012, 05, 31)) datetime.datetime(2012, 4, 30, 0, 0) ''' if date.month > 1: last_year = date.year last_month = date.month - 1 else: last_year = date.year - 1 last_month = 12 current_date_range = calendar.monthrange(date.year, date.month) last_date_range = calendar.monthrange(last_year, last_month) if date.day == current_date_range[1]: last_day = last_date_range[1] else: if date.day > last_date_range[1]: last_day = last_date_range[1] else: last_day = date.day earlier = datetime(last_year, last_month, last_day) return earlier
def save(self, *args, **kwargs): # Overridden save() forces the date of self.end to be the last day of that given month. # Eg. if self.end is initially declared as 5 May 2010, we now force it to become 31 May 2010 before actually save()'ing the object. # But first, is self.end even specified? if not self.valid_till: self.valid_till = self.start last_day = calendar.monthrange(self.valid_till.year, self.valid_till.month)[1] self.valid_till = datetime.date(self.valid_till.year, self.valid_till.month, last_day) # Force start date to be normalised as 1st day of the month if self.start.day != 1: self.start = datetime.date(self.start.year, self.start.month, 1) # If we notice the Contract is now Terminated, and the end date has not been set, set the end date if self.status == 'TER' and self.end is None: today = datetime.date.today() self.end = datetime.date(today.year, today.month, calendar.monthrange(today.year, today.month)[1]) # If the model has been saved already, ie. has an id, force it to update # otherwise, insert a new record if self.id: kwargs['force_update'] = True kwargs['force_insert'] = False else: kwargs['force_insert'] = True kwargs['force_update'] = False super(Contract, self).save(*args, **kwargs)
def compute_depreciation(self, date, dates): """ Returns the depreciation amount for an asset on a certain date. """ amount = (self.value - self.get_depreciated_amount() - self.residual_value) if self.depreciation_method == 'linear': start_date = max([self.start_date - relativedelta.relativedelta(days=1)] + [l.date for l in self.lines]) first_delta = dates[0] - start_date if len(dates) > 1: last_delta = dates[-1] - dates[-2] else: last_delta = first_delta if self.frequency == 'monthly': _, first_ndays = calendar.monthrange( dates[0].year, dates[0].month) _, last_ndays = calendar.monthrange( dates[-1].year, dates[-1].month) elif self.frequency == 'yearly': first_ndays = 365 + calendar.isleap(dates[0].year) last_ndays = 365 + calendar.isleap(dates[-1].year) first_ratio = Decimal(first_delta.days) / Decimal(first_ndays) last_ratio = Decimal(last_delta.days) / Decimal(last_ndays) depreciation = amount / ( len(dates) - 2 + first_ratio + last_ratio) if date == dates[0]: depreciation *= first_ratio elif date == dates[-1]: depreciation *= last_ratio return self.company.currency.round(depreciation)
def to_date_range(month=None,year=None): if month is not None and year is not None: dates = { 'jan' : 1, 'feb' : 2, 'mar' : 3, 'apr' : 4, 'may' : 5, 'jun' : 6, 'jul' : 7, 'aug' : 8, 'sep' : 9, 'oct' : 10, 'nov' : 11, 'dec' : 12 } m = dates[month] d = calendar.monthrange(year,m)[1] return (("%s/1/%s" % (m,year)),("%s/%s/%s" % (m,d,year))) else: t = datetime.today() m = t.month y = t.year d = calendar.monthrange(y,m)[1] return (("%s/1/%s" % (m,y)),("%s/%s/%s" % (m,d,y)))
def compute_additional_values_yellow_table(self, table_header, table_results): self.LOG.debug(table_header) table_header.remove('last_month_total') table_header.remove('last_month_date') table_header.append('Estimation') table_header.append('Est diff') now = datetime.datetime.now() try: last_month = time.strptime(table_results[0].get('last_month_date',''), "%Y/%m/%d") last_month_no, last_month_days = calendar.monthrange(last_month.tm_year, last_month.tm_mon) month_no, month_days = calendar.monthrange(now.year, now.month) for row in table_results: try: estimation = ((int(float(row['last_month_total']) * 100) / last_month_days) * month_days )/ 100 row['Estimation'] = estimation estimation_current_day = ((int(float(row['last_month_total']) * 100) / last_month_days) * now.day )/ 100 row['Est diff'] = float(row['Costs']) - estimation_current_day except KeyError: row['Estimation'] = row['Est diff'] = 0 except ValueError: for row in table_results: row['Estimation'] = row['Est diff'] = '0' self.LOG.debug(table_results)
def dfc_month_greg(month_start_date='1-1-2000', supply=0, demand=[0]): """ Calculate DFC for a starting inventory and monthly demand series. """ remaining = supply dfc = 0 month_start_date = datetime.datetime.strptime(month_start_date, '%m-%d-%Y').date() days_in_month = monthrange(month_start_date.year, month_start_date.month)[1] for month in demand: if remaining > month: dfc += days_in_month remaining -= month else: dfc += (remaining / (month / days_in_month)) break days_in_month = monthrange(month_start_date.year, month_start_date.month % 12 + 1)[1] return dfc
def dfc_month_greg_reverse(month_start_date='1-1-2000', dfc=0, demand=[0]): """ Calculates the starting inventory required to maintain a specified DFC over a given monthly demand series. """ supply = 0 month_start_date = datetime.datetime.strptime(month_start_date, '%m-%d-%Y').date() days_in_month = monthrange(month_start_date.year, month_start_date.month)[1] for month in demand: if dfc > days_in_month: supply += month dfc -= days_in_month else: supply += (dfc * (month / days_in_month)) break days_in_month = monthrange(month_start_date.year, month_start_date.month % 12 + 1)[1] return supply
def get_days_in_month(month_edit, year_edit, date_time): ''' Get the number of days in the month. Assumes non-None month and year field. Returns 31 if month field is zero or not valid and 28 if Feb, but year not valid. ''' if not date_time.month_is_valid: LOGGER.debug("get_days_in_month returning 31") return(31) month_num = int(month_edit.get_text()) if (month_num == 0): return(31) # if month set to Feb, check for leap year if (month_num == 2): if not date_time.year_is_valid: LOGGER.debug("get_days_in_month returning 28") return(28) else: cur_year = year_edit.get_text() LOGGER.debug("cur_year %s", cur_year) if len(cur_year) == 4: return (calendar.monthrange(int(cur_year), 2)[1]) now = datetime.datetime.now() return (calendar.monthrange(now.year, month_num)[1])
def apply(self, other): n = self.n if self._normalizeFirst: other = normalize_date(other) wkday, nDaysInMonth = calendar.monthrange(other.year, self.month) lastBDay = nDaysInMonth - max(((wkday + nDaysInMonth - 1) % 7) - 4, 0) years = n if n > 0: if (other.month < self.month or (other.month == self.month and other.day < lastBDay)): years -= 1 elif n <= 0: if (other.month > self.month or (other.month == self.month and other.day > lastBDay)): years += 1 other = other + relativedelta(years=years) _, days_in_month = calendar.monthrange(other.year, self.month) result = datetime(other.year, self.month, days_in_month) if result.weekday() > 4: result = result - BDay() return result
def calendar_(): cal = calendar.month(2017, 6) # by default w=2 l=1 print cal # 2017年6月份日历 print '--------------------' # calendar内置函数 #calendar of year 2017: c=distance(month); l=line(week); w=distance(day) print calendar.calendar(2017, w=2, l=1, c=6) #lenth(line)= 21* W+18+2* C print calendar.firstweekday() # start weekday, 0 by default, i.e. Monday # calendar.setfirstweekday(weekday) # 0(Monday) to 6(Sunday) print calendar.isleap(2017) # return True or False print calendar.leapdays(2000, 2016) # number of leap years between year 1 and year 2 print calendar.month(2017, 6) print calendar.monthcalendar(2017, 6) print calendar.monthrange(2017, 6) # return (a, b) a=starting weekday b=days in month calendar.prcal(2017, w=2, l=1, c=4) # equals to print calendar.calendar(2017, w=2, l=1, c=4) calendar.prmonth(2017, 6) # equals to print calendar.month(2017, 6) print calendar.timegm(time.localtime()) #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍 print calendar.weekday(2017, 6, 30) # calendar.weekday(year,month,day) return date code
def get_nth_day_of_month(self, n, weekday, month, year=None): # doesn't set the time list # returns the day of the month 1..31 if not year: year = self.time_list[YEAR] firstday, daysinmonth = calendar.monthrange(year, month) # firstday is MON, weekday is WED -- start with 3rd day of month # firstday is WED, weekday is MON -- # firstday = weekday if firstday < weekday: date = weekday - firstday + 1 # 2 - 0 + 1 elif firstday > weekday: date = 7 - (firstday - weekday) + 1 else: date = 1 if n == 1: return date for i in range(1, n): date += 7 if month in HAVE_30_DAYS and date > 30: raise IndexError if month in HAVE_31_DAYS and date > 31: raise IndexError if month == FEB and date > 28: ignore, daysinfeb = calendar.monthrange(year, FEB) if date > daysinfeb: raise IndexError return date
def get_nth_day_of_month(n, weekday, month, year): firstday, daysinmonth = calendar.monthrange(year, month) # firstday is MON, weekday is WED -- start with 3rd day of month # firstday is WED, weekday is MON -- # firstday = weekday if firstday < weekday: date = weekday - firstday + 1 # 2 - 0 + 1 elif firstday > weekday: date = 7 - (firstday - weekday) + 1 else: date = 1 if n == 1: return date for i in range(1, n): date += 7 if month in HAVE_30_DAYS and date > 30: raise IndexError if month in HAVE_31_DAYS and date > 31: raise IndexError if month == FEB and date > 28: ignore, daysinfeb = calendar.monthrange(year, FEB) if date > daysinfeb: raise IndexError return date
def replace_u_end_day(day, year, month): """Find the latest legitimate day.""" day = day.lstrip('-') year = int(year) month = int(month.lstrip('-')) if day == 'uu' or day == '3u': # Use the last day of the month for a given year/month. return str(calendar.monthrange(year, month)[1]) if day == '0u' or day == '1u': return day.replace('u', '9') if day == '2u' or day == 'u9': if month != '02' or calendar.isleap(year): return '29' elif day == '2u': # It is Feburary and not a leap year. return '28' else: # It is February, not a leap year, day ends in 9. return '19' # 'u2' 'u3' 'u4' 'u5' 'u6' 'u7' 'u8' if 1 < int(day[1]) < 9: return day.replace('u', '2') # 'u0' 'u1' if day == 'u1': if calendar.monthrange(year, month)[1] == 31: # See if the month has a 31st. return '31' else: return '21' if day == 'u0': if calendar.monthrange(year, month)[1] >= 30: return '30' else: return '20'
def _parse_month(self, crontab, next_month=False): now = self._sh.now() minute, hour, day, wday = crontab.split(' ') # evaluate the crontab strings minute_range = self._range(minute, 00, 59) hour_range = self._range(hour, 00, 23) if not next_month: mdays = calendar.monthrange(now.year, now.month)[1] elif now.month == 12: mdays = calendar.monthrange(now.year + 1, 1)[1] else: mdays = calendar.monthrange(now.year, now.month + 1)[1] if wday == '*' and day == '*': day_range = self._day_range('0, 1, 2, 3, 4, 5, 6') elif wday != '*' and day == '*': day_range = self._day_range(wday) elif wday != '*' and day != '*': day_range = self._day_range(wday) day_range = day_range + self._range(day, 0o1, mdays) else: day_range = self._range(day, 0o1, mdays) # combine the differnt ranges event_range = sorted([str(day) + '-' + str(hour) + '-' + str(minute) for minute in minute_range for hour in hour_range for day in day_range]) if next_month: # next month next_event = event_range[0] next_time = now + dateutil.relativedelta.relativedelta(months=+1) else: # this month now_str = now.strftime("%d-%H-%M") next_event = self._next(lambda event: event > now_str, event_range) if not next_event: return False next_time = now day, hour, minute = next_event.split('-') return next_time.replace(day=int(day), hour=int(hour), minute=int(minute), second=0, microsecond=0)
def addmonths(sourcedate,months): month = sourcedate.month - 1 + months year = sourcedate.year + month / 12 month = month % 12 + 1 day = min(sourcedate.day,calendar.monthrange(year,month)[1]) print calendar.monthrange(year,month)[1] return date(year,month,day)
def offset_timeslot(cls, timeslot, year=0, month=0, day=0, hour=0, minute=0, dekade=0): new_year = timeslot.year + year if month != 0: month_years = (timeslot.month + month - 1) // 12 new_year += month_years new_month = (timeslot.month + month) % 12 new_month = 12 if new_month == 0 else new_month month_n_days = monthrange(new_year, new_month)[1] new_day = timeslot.day if timeslot.day < month_n_days else month_n_days candidate = datetime(new_year, new_month, new_day, timeslot.hour, timeslot.minute) offset_time = (hour * 60 * 60) + minute * 60 if dekade != 0: t_day = timeslot.day first_day = 1 if t_day < 11 else (11 if t_day < 21 else 21) timeslot_first_day = datetime(timeslot.year, timeslot.month, first_day, timeslot.hour, timeslot.minute) end_timeslot = timeslot_first_day forward = dekade / abs(dekade) > 0 factor = 1 if forward else -1 for d in range(abs(dekade)): if (t_day < 21 and forward) or (t_day > 1 and not forward): end_timeslot += factor * timedelta(days=10) else: the_ts = end_timeslot if forward else \ end_timeslot - timedelta(days=1) n_days = monthrange(the_ts.year, the_ts.month)[1] - 20 end_timeslot += factor * timedelta(days=n_days) day += factor * abs((end_timeslot - timeslot).days) delta = timedelta(days=day, seconds=offset_time) return candidate + delta
def getBarChartInfoByPinForYear(cursor, pinset_id): today = datetime.datetime.now() start_date = datetime.datetime(day = 1, month=1, year=today.year).replace(tzinfo=utc) end_date = datetime.datetime(day=monthrange(today.year, today.month)[1], month=today.month, year=today.year).replace(tzinfo=utc) data = [] aux = [] aux.append("Cost") data.append(aux) aux = [] sDate = start_date timedelta = datetime.timedelta(days=1) while sDate.month <= end_date.month : monthDays= monthrange(sDate.year, sDate.month)[1] fDate = datetime.datetime(day=monthDays, month=sDate.month, year = sDate.year).replace(tzinfo=utc) cursor.execute( 'SELECT tarifica_pinsetdailydetail.id, SUM(tarifica_pinsetdailydetail.cost) AS cost \ FROM tarifica_pinsetdailydetail WHERE date >= %s AND date <= %s AND pinset_id = %s ', [sDate, fDate ,pinset_id]) monthCost = dictfetchall(cursor) month = getMonthName(sDate.month) if monthCost[0]['cost'] is None: aux.append([month, 0]) else: aux.append([month, monthCost[0]['cost']]) if fDate.month == 12: break #print aux sDate = datetime.datetime(day=1, month=fDate.month+1, year=fDate.year).replace(tzinfo=utc) data.append(aux) return data
def adjust_each_metric_in_month(self, dates, value=None): if set([self.selected_metric]) & (set(self.names.metric.runtime) | set(self.names.metric.runtimeusers)): selected = self.get_selected_instance() t_start = selected["t_start"] t_end = selected["t_end"] first_month = datetime(t_start.year, t_start.month, 1) end_of_first_month = datetime(t_start.year, t_start.month, monthrange( t_start.year, t_start.month)[1], 23, 59, 59) end_month = datetime( t_end.year, t_end.month, 1) # datetime.combine(t_end.date(), datetime.strptime("00:00:00", "%H:%M:%S").time()) start_of_end_month = end_month for month_key, month_value in dates.iteritems(): days = monthrange(month_key.year, month_key.month)[1] dates[month_key] = self.do_time_conversion(86400 * days) if first_month == end_month: dates[first_month] = self.do_time_conversion( (t_end - t_start).seconds) else: dates[first_month] = self.do_time_conversion( (end_of_first_month - t_start).seconds) dates[end_month] = self.do_time_conversion( (t_end - start_of_end_month).seconds) elif set([self.selected_metric]) & set(self.names.metric.countusers): for entry_date, entry_value in dates.iteritems(): new_value = self._is_unique( self.selected_metric + self.period + str(entry_date), value) if new_value is None: dates[entry_date] = new_value
def bug_view(request): bugname=request.user.last_name if request.GET: l=request.GET #[0123-56] choice_date=l['yearmonth'] choice_year = int(choice_date[0:4]) choice_month = int(choice_date[-2:]) else: today = datetime.date.today() choice_year = int(today.year) choice_month = int(today.month) result={} text=[] this_month_day = calendar.monthrange(choice_year,choice_month) #当前月份天数 this_month_day this_month_day=this_month_day[1] #当前月份第一天为周几 first_day first_day=datetime.datetime(choice_year,choice_month,1).strftime("%w"); #上个月的天数 last_month_day last_year = choice_year last_month = choice_month-1 if last_month == 0: last_year=last_year-1 last_month=12 last_month_day=calendar.monthrange(last_year,last_month) last_month_day=last_month_day[1] #尝试输出元组 i=int(first_day)-1 while(i>0): day_date=-(int(last_month_day)-i+1) result[day_date]=text i=i-1 i=1 while(i<=int(this_month_day)): text=[] day_date=i if i<10: j="0"+str(i) else: j=str(i) daydate=str(choice_year)+'-'+str(choice_month)+'-'+j gi=BugDetail.objects.filter(finish_date=daydate) for a in gi: text.append(a.person.name) result[day_date]=text i=i+1 i=1 endbox=42-int(this_month_day)-int(first_day)+1 while(i<=endbox): day_date=100+i result[day_date]=text i=i+1 tabledate=sorted(result.iteritems(),key=lambda asd:asd[0] ,reverse = False) if int(choice_month)<10: choice_month='0'+str(choice_month) return render_to_response('bugview/bug_view.html',{'tabledate':tabledate, 'choice_year':choice_year, 'choice_month':choice_month, 'bugname':bugname},context_instance=RequestContext(request))
def provider_year(self): self.PARAMS.YEAR = int(self.yearbox.get()) if self.PARAMS.YEAR == self.PARAMS.THIS_YEAR: self.PARAMS.MONTH = self.PARAMS.THIS_MONTH if self.PARAMS.MONTH > self.PARAMS.THIS_MONTH else self.PARAMS.MONTH self.PARAMS.MONTH_LIST = list(range(1,self.PARAMS.THIS_MONTH+1)) elif self.PARAMS.YEAR == self.PARAMS.YEAR_INI: if self.PARAMS.MONTH < self.PARAMS.MONTH_INI: self.PARAMS.MONTH = self.PARAMS.MONTH_INI self.PARAMS.MONTH_LIST = list(range(self.PARAMS.MONTH_INI,13)) else: self.PARAMS.MONTH_LIST = list(range(1,13)) self.month_var.set(self.PARAMS.MONTH) self.monthbox['values'] = self.PARAMS.MONTH_LIST self.PARAMS.DAY_LIST = list(range(1,monthrange(self.PARAMS.YEAR,self.PARAMS.MONTH)[1]+1)) if self.PARAMS.YEAR == self.PARAMS.THIS_YEAR and self.PARAMS.MONTH == self.PARAMS.THIS_MONTH: self.PARAMS.DAY_LIST = list(range(1,self.PARAMS.THIS_DAY+1)) if self.PARAMS.DAY > self.PARAMS.THIS_DAY: self.PARAMS.DAY = self.PARAMS.THIS_DAY else: self.PARAMS.DAY_LIST = list(range(1,monthrange(self.PARAMS.YEAR,self.PARAMS.MONTH)[1]+1)) self.day_var.set(self.PARAMS.DAY) self.daybox['values'] = self.PARAMS.DAY_LIST
def move_previous_month(self, *args, **kwargs): if self.date.month == 1: self.date = date(self.date.year - 1, 12, min(self.date.day,calendar.monthrange(self.date.year,12)[1])) else: self.date = date(self.date.year, self.date.month -1, min(self.date.day,calendar.monthrange(self.date.year, self.date.month -1)[1])) self.populate_header() self.populate_body()
def periodic_payment(self): """ Вычисляем ежедневный платеж Если подписка не с ежедневным платежом, возвращает цену подписки """ today = timezone.localtime(timezone.now()) transaction_amount = 0 if self.plan.payment_period == 'everyday': if self.plan.period == 'everyday': transaction_amount = self.plan.price # Если срок подписки 1 месяц, вычисляем платеж исходя из количества дней в текущем месяце elif self.plan.period == 'monthly': days_in_month = calendar.monthrange(today.year, today.month) days_in_month = days_in_month[1] transaction_amount = self.plan.price / days_in_month # Если срок подписки 3 месяца, делим стоимость подписки на 3 дальше так же. Далее по аналогии. elif self.plan.period == 'three_months': days_in_month = calendar.monthrange(today.year, today.month) days_in_month = days_in_month[1] transaction_amount = self.plan.price / 3 / days_in_month elif self.plan.period == 'half-year': days_in_month = calendar.monthrange(today.year, today.month) days_in_month = days_in_month[1] transaction_amount = self.plan.price / 6 / days_in_month elif self.plan.period == 'yearly': days_in_month = calendar.monthrange(today.year, today.month) days_in_month = days_in_month[1] transaction_amount = self.plan.price / 12 / days_in_month else: transaction_amount = self.plan.price return transaction_amount.quantize(Decimal('.00'))
def move_next_month(self, *args, **kwargs): if self.date.month == 12: self.date = date(self.date.year + 1, 1,min(self.date.day,calendar.monthrange(self.date.year,1)[1]) ) else: self.date = date(self.date.year, self.date.month + 1,min(self.date.day,calendar.monthrange(self.date.year, self.date.month +1)[1])) self.populate_header() self.populate_body()
def days_of_month(date): aux = date - datetime.timedelta(date.weekday()) if aux.month == date.month: aux = aux - datetime.timedelta(7 * ((aux.day / 7) + 1)) days = [] months = [] if aux.day != 1: if date.month > 1: before_month = calendar.monthrange(date.year, date.month-1)[1] else: before_month = calendar.monthrange(date.year-1, 12)[1] days = range(aux.day, before_month+1) for elem in days: months.append(aux.month) this_month = calendar.monthrange(date.year, date.month)[1] this_days = range(1, this_month+1) days.extend(this_days) for elem in this_days: months.append(date.month) aux = datetime.date(date.year, date.month, this_month) if aux.weekday() != 6: aux = aux + datetime.timedelta(6-aux.weekday()) this_days = range(1, aux.day+1) days.extend(this_days) for elem in this_days: months.append(aux.month) return days, months
def deadlineToTime(param): ''' Compute time for structed deadline ''' import calendar now = datetime.datetime.now() settime = lambda cur, now: now+(cur - now) if param == 'endday': cur = datetime.datetime(year=now.year, month=now.month, \ day=now.day, hour=23, minute=59, second=59) return settime(cur, now) if param == 'endweek': v, res = calendar.monthrange(now.year, now.month) weekday = now.day + 7 - now.weekday() month = now.month day = now.day if weekday > res: month = now.month + 1 day = weekday - res cur = datetime.datetime(year=now.year, month=month, \ day=day, hour=23, minute=59, second=59) return settime(cur, now) if param == 'endmonth': v, res = calendar.monthrange(now.year, now.month) cur = datetime.datetime(year=now.year, month=now.month, \ day=res, hour=23, minute=59, second=59) return settime(cur, now)
def _argcheck_day(day, month, year): if not isinstance(day, numbers.Integral): msg = '__init__() day: Integer argument expected, got {}' raise TypeError(msg.format(type(day))) if not 1 <= day <= calendar.monthrange(year, month)[1]: msg = '__init__() day must be in 1..{}' raise ValueError(msg.format(calendar.monthrange(year, month)[1]))
def obtemDiasDaSemana(self,deslocamento=0): dias = [0,0,0,0,0,0,0] hoje=datetime.today() semanaHoje = hoje.isocalendar()[1] if deslocamento!=0: semanaHoje = hoje.isocalendar()[1]+deslocamento proximoMes=0 if (hoje.day+deslocamento*7) > calendar.monthrange(hoje.year,hoje.month)[1]: proximoMes=1 hoje=datetime(hoje.year,hoje.month+proximoMes,(hoje.day+deslocamento*7)%calendar.monthrange(hoje.year,hoje.month+proximoMes)[1]) umDia = timedelta(days=1) dDestaSemana = hoje.weekday() pD=0 uD=6 while pD <= uD: if pD <=dDestaSemana: dEmQuestao = hoje-umDia*pD dias[dDestaSemana-pD]=str(dEmQuestao.day)+'/'+str(dEmQuestao.month)+'/'+str(dEmQuestao.year) else: dEmQuestao = hoje+umDia*(pD-dDestaSemana) dias[pD]=str(dEmQuestao.day)+'/'+str(dEmQuestao.month)+'/'+str(dEmQuestao.year) pD=pD+1 return dias
def _next_repeat(self, date): if self.repeat == "daily": return date elif self.repeat == "monthly_by_day_of_month": if date.day > self.start.day: # skip to next month date = date.replace( day=1, month=(date.month + 1) % 12, year=date.year + int(math.floor((date.month + 1) / 12)) ) if self.start.day > calendar.monthrange(date.year, date.month)[1]: date = date.replace(day=calendar.monthrange(date.year, date.month)[1]) else: date = date.replace(day=self.start.day) else: weekday = date.weekday() if self.repeat == "weekdays": date = date + timedelta(days=7 - weekday) if (weekday == 5 or weekday == 6) else date elif self.repeat == "weekends": date = date + timedelta(days=5 - weekday) if (0 <= weekday <= 4) else date else: # must be weekly date = ( date + timedelta(days=self.start.weekday() - weekday) if self.start.weekday() >= weekday else date + timedelta(days=7 - weekday + self.start.weekday()) ) return date
def match_date(date, date_pattern): """ Match a specific date, a four-tuple with no special values, with a date pattern, four-tuple possibly having special values. """ # unpack the date and pattern year, month, day, day_of_week = date year_p, month_p, day_p, day_of_week_p = date_pattern # check the year if year_p == 255: # any year pass elif year != year_p: # specific year return False # check the month if month_p == 255: # any month pass elif month_p == 13: # odd months if (month % 2) == 0: return False elif month_p == 14: # even months if (month % 2) == 1: return False elif month != month_p: # specific month return False # check the day if day_p == 255: # any day pass elif day_p == 32: # last day of the month last_day = calendar.monthrange(year + 1900, month)[1] if day != last_day: return False elif day_p == 33: # odd days of the month if (day % 2) == 0: return False elif day_p == 34: # even days of the month if (day % 2) == 1: return False elif day != day_p: # specific day return False # check the day of week if day_of_week_p == 255: # any day of the week pass elif day_of_week != day_of_week_p: # specific day of the week return False # all tests pass return True
import datetime import calendar # Get the first and last day of the month for query input_text = raw_input('Enter the year and month : YYYY-MM: ').strip() date = datetime.datetime(int(input_text.split("-")[0]),int(input_text.split("-")[1]),1).date() print date first_day = str(date.replace(day = 1)) #get last day last_day = str(date.replace(day = calendar.monthrange(date.year, date.month)[1])) print first_day, last_day
def add_months(sourcedate, months): month = sourcedate.month - 1 + months year = int(sourcedate.year + month / 12) month = month % 12 + 1 day = min(sourcedate.day, calendar.monthrange(year, month)[1]) return dt.date(year, month, day)
def days_in_month(self): return calendar.monthrange(self.year, self.month)[1]
#iDTime = datetime(2006,1,1,6) # HAPPI #eDTime = datetime(2014,12,31,18) # HAPPI #-- argv ---------------- largv = sys.argv if len(largv) > 1: prj, model, run, res, noleap = largv[1:1 + 5] if noleap == "True": noleap = True elif noleap == "False": noleap = False else: print "check noleap", noleap sys.exit() iYear, iMon, eYear, eMon = map(int, largv[6:]) eDay = calendar.monthrange(eYear, eMon)[1] #iDTime = datetime(iYear,iMon,1,6) iDTime = datetime(iYear, iMon, 1, 0) # 2018/10/25 eDTime = datetime(eYear, eMon, eDay, 18) #------------------------- dDTime = timedelta(hours=6) ret_lDTime = {False: util.ret_lDTime, True: util.ret_lDTime_noleap}[noleap] lDTime = ret_lDTime(iDTime, eDTime, dDTime) miss = -9999.0 miss_int = -9999 cfg = config.cfg cfg['prj'] = prj # for ConstCyclone
def getMonthDays(self, year, month): import calendar monthRange = calendar.monthrange(int(year), int(month)) return monthRange[1]
def defuzz(formdata: dict, nodate: bool = False, list_override: typing.Optional[str] = None) -> dict: # Default to 30 day date range daterange = {"gt": "now-30d", "lt": "now+1d"} # Custom date range? # If a month is the only thing, fake start and end if "date" in formdata and "e" not in formdata: formdata["s"] = formdata["date"] formdata["e"] = formdata["date"] # classic start and end month params if "s" in formdata and "e" in formdata: if not re.match(r"\d{4}-\d{1,2}$", formdata["s"]): raise ValueError("Keyword 's' must be of type YYYY-MM") if not re.match(r"\d{4}-\d{1,2}$", formdata["e"]): raise ValueError("Keyword 'e' must be of type YYYY-MM") syear, smonth = formdata["s"].split("-", 1) eyear, emonth = formdata["e"].split("-", 1) _estart, eend = calendar.monthrange(int(eyear), int(emonth)) daterange = { "gt": "%04u/%02u/01 00:00:00" % (int(syear), int(smonth)), "lt": "%04u/%02u/%02u 23:59:59" % (int(eyear), int(emonth), eend), } # days ago to start, and number of days to match elif "dfrom" in formdata and "dto" in formdata: dfrom = formdata["dfrom"] dto = formdata["dto"] if re.match(r"\d+$", dfrom) and re.match(r"\d+$", dto): ef = int(dfrom) et = int(dto) if ef > 0 and et > 0: if et > ef: et = ef # avoid overruning into the future daterange = { "gte": "now-%dd" % ef, "lte": "now-%dd" % (ef - et), } else: raise ValueError("Keywords 'dfrom' and 'dto' must be numeric") # Advanced date formatting elif "d" in formdata: # The more/less than N days/weeks/months/years ago m = re.match(r"^(lte|gte)=([0-9]+[Mwyd])$", formdata["d"]) if m: t = m.group(1) r = m.group(2) if t == "lte" and r: daterange = {"gt": "now-%s" % r} elif t == "gte" and r: daterange = {"lt": "now-%s" % r} else: # simple one month listing m = re.match(r"^(\d\d\d\d-\d+)$", formdata["d"]) if m: xdate = m.group(1) dyear, dmonth = xdate.split("-", 1) daterange = { "gte": "%04u-%02u-01||/M" % (int(dyear), int(dmonth)), "lte": "%04u-%02u-01||/M" % (int(dyear), int(dmonth)), "format": "yyyy-MM-dd", } else: # dfr and dto defining a time span m = re.match(r"^dfr=(\d\d\d\d-\d+-\d+)\|dto=(\d\d\d\d-\d+-\d+)$", formdata["d"]) if m: dfr = m.group(1) dto = m.group(2) syear, smonth, sday = dfr.split("-", 2) eyear, emonth, eday = dto.split("-", 2) daterange = { "gt": "%04u/%02u/%02u 00:00:00" % (int(syear), int(smonth), int(sday)), "lt": "%04u/%02u/%02u 23:59:59" % (int(eyear), int(emonth), int(eday)), } # List parameter(s) if list_override: # Certain requests use the full list ID as a single variable. Allow for that if so. if not list_override.count("@") == 1: raise ValueError("list_override must contain exactly one @ character") listname, fqdn = list_override.split("@", 1) else: fqdn = formdata.get("domain", '') # Must be provided listname = formdata.get("list", '') # Must be provided if not fqdn: raise ValueError("You must specify a domain part of the mailing list(s) to search, or * for wildcard search.") if not listname: raise ValueError("You must specify a list part of the mailing list(s) to search, or * for wildcard search.") if "@" in listname: raise ValueError("The list component of the List ID(s) cannot contain @, please use both list and domain keywords for searching.") list_raw = "<%s.%s>" % (listname, fqdn) # Default is to look in a specific list query_list_hash: typing.Dict = {"term": {"list_raw": list_raw}} # *@fqdn match? if listname == "*" and fqdn != "*": query_list_hash = {"wildcard": {"list_raw": {"value": "*.%s>" % fqdn}}} # listname@* match? if listname != "*" and fqdn == "*": query_list_hash = {"wildcard": {"list_raw": "<%s.*>" % listname}} # *@* ?? if listname == "*" and fqdn == "*": query_list_hash = {"wildcard": {"list_raw": "*"}} must = [query_list_hash] must_not = [] # Append date range if not excluded if not nodate: must.append({"range": {"date": daterange}}) # Query string search: # - foo bar baz: find emails with these words # - orange -apples: fond email with oranges but not apples # - "this sentence": find emails with this exact string if "q" in formdata: qs = formdata["q"].replace(":", "") try: bits = shlex.split(qs) except ValueError: # Uneven number of quotes, default to split on whitespace instead bits = qs.split() query_should_match = [] query_should_not_match = [] for bit in bits: force_positive = False # Translate -- into a positive '-', so you can find "-1" etc if bit[0:2] == "--": force_positive = True bit = bit[1:] # Negatives if bit[0] == "-" and not force_positive: query_should_not_match.append(bit[1:]) # Positives else: query_should_match.append(bit) if query_should_match: query_should_match_expanded = [] for x in query_should_match: query_should_match_expanded.append( { "bool": { "should": [ { "multi_match": { "fields": ["from", "body", "subject"], "query": x, "type": "phrase", }, }, ] } } ) xmust = {"bool": {"minimum_should_match": len(query_should_match), "should": query_should_match_expanded}} must.append(xmust) for x in query_should_not_match: must_not.append( { "match": { "subject": x, } } ) must_not.append( { "match": { "from": x, } } ) must_not.append( { "match": { "body": x, } } ) # Header parameters for header in ["from", "subject", "body", "to"]: hname = "header_%s" % header if hname in formdata: hvalue = formdata[hname] must.append({"match_phrase": {header: hvalue}}) query_as_bool = {"must": must} if must_not: query_as_bool["must_not"] = must_not return query_as_bool
def download_http(download_path, host, directory, filename, filedate, dirstruct, ffilter=None, begin=None, end=datetime.now()): """Download data via HTTP Parameters ---------- download_path : str, optional Path where to save the downloaded files. host : str Link to host. directory : str Path to data on host. filename : str Structure/convention of the file name. filedate : dict Dict which points to the date fields in the filename. dirstruct : list of str Folder structure on host, each list element represents a subdirectory. ffilter : str, optional Used for filtering files on a server, defaults to None. begin : datetime, optional Set either to first date of remote repository or date of last file in local repository. end : datetime, optional Date until which data should be downloaded. Returns ------- bool true if data is available, false if not """ if begin is None: begin = datetime(1900, 1, 1) if end is None: end = datetime.now() print('[INFO] downloading data from ' + str(begin) + ' - ' + str(end)) # create daterange on monthly basis mon_from = datetime(begin.year, begin.month, 1) mon_to = datetime(end.year, end.month, 1) daterange = pd.date_range(start=mon_from, end=mon_to, freq='MS') if '{MM}' in filename: leading_month = True else: leading_month = False path = host + directory if not os.path.exists(download_path): os.makedirs(download_path) # loop through daterange for i, dat in enumerate(daterange): year = str(dat.year) month = str("%02d" % (dat.month, )) if dirstruct is not None and dirstruct == ['YYYY']: path = host + directory + year + '/' elif dirstruct == ['YYYY', 'MM']: path = host + directory + year + '/' + month + '/' elif dirstruct == ['YYYY', 'M']: path = host + directory + year + '/' + dat.month + '/' else: path = host + directory # + subdirectories! if leading_month is True: month = str("%02d" % (dat.month, )) fname = filename.replace('{YYYY}', year).replace('{MM}', month) else: fname = filename.replace('{YYYY}', year).replace('{M}', month) files = [] if '{P}' in filename: dekads = range(3) # get dekad of first and last interval based on input dates if begin.year == end.year and begin.month == end.month: if begin.day < 11: if end.day > 10: if end.day > 20: dekads = range(3) else: dekads = [0, 1] else: dekads = [0] elif begin.day > 10 and begin.day < 21: if end.day < 21: dekads = [1] elif end.day > 20: dekads = [1, 2] else: dekads = [2] else: if i == 0 and begin.day > 1: if begin.day < 11: dekads = [0, 1, 2] elif begin.day >= 11 and begin.day < 21: dekads = [1, 2] elif begin.day == 21: dekads = [2] elif i == (len(daterange) - 1) and end.day < 21: if end.day < 11: dekads = [0] else: dekads = [0, 1] # loop through dekads for j in dekads: filepath = path + fname.replace('{P}', str(j + 1)) files.append(filepath) elif '{D}' in filename or '{DD}': if '{DD}' in filename: leading_day = True else: leading_day = False mr = calendar.monthrange(2014, 7) fday = mr[0] lday = mr[1] + 1 if i == 0 and begin.day > 1: days = range(begin.day, lday) elif i == (len(daterange) - 1) and end.day < lday: days = range(fday, end.day + 1) else: days = range(fday, lday) # loop through dekads for j in days: if leading_day is True: day = str("%02d" % (j)) filepath = path + fname.replace('{DD}', day) else: filepath = path + fname.replace('{D}', str(j + 1)) files.append(filepath) else: files.append(fname) for fp in files: newfile = os.path.join(download_path, fp.split('/')[-1]) if os.path.exists(newfile): continue try: r = requests.get(fp, timeout=20.) except ConnectionError: print '[ERROR] Could not connect to resource, skipping...' continue except Timeout: print '[WARNING] File not available at resource, skipping...' continue if r.status_code == 200: # check if year folder is existing if ffilter is None or ffilter in os.path.split(fp)[-1]: if not os.path.exists(download_path): print( '[INFO] output path does not exist...' 'creating path') os.makedirs(download_path) # download file newfile = os.path.join(download_path, fp.split('/')[-1]) r = requests.get(fp, stream=True) with open(newfile, 'wb') as f: f.write(r.content) if len(files) > 0: return True else: return False
print(time.localtime(time.time())) print(time.asctime(time.localtime(time.time()))) #날짜 시간으로 print(time.ctime()) # ctime 은 항상 현재 시간만 돌려줌 #time.strftime('출력할 형식 포맷 코드', time.localtime(time.time()))) print(time.strftime('%x', time.localtime(time.time()))) print(time.strftime('%c', time.localtime(time.time()))) for i in range(10): print(i) time.sleep(0.1) # 1초간격쉬기 0.5도 가능 여러가지 가능 # calendar print(calendar.calendar(2020)) #1~12월 다보여줌 print(calendar.prcal(2020)) #위와 똑같은 결과 print(calendar.prmonth(2020, 2)) # 2020년 2월 달력보여줘 print(calendar.weekday(2020, 12, 31)) # 0월 1화 2수 3목 4금 5토 6일 print(calendar.monthrange(2020, 12)) # 결과(요일, 날짜수) = (화요일 1, 31) # random print(random.random()) # 난수(규칙이 없는 임의의 수)값 print(random.randint(1, 10)) print(random.randint(1, 55)) def random_pop(data): number = random.randint(0, len(data) - 1) return data.pop(number) if __name__ == "__main__": data = [1, 2, 3, 4, 5] while data:
def match_weeknday(date, weeknday): """ Match a specific date, a four-tuple with no special values, with a BACnetWeekNDay, an octet string with three (unsigned) octets. """ # unpack the date year, month, day, day_of_week = date last_day = calendar.monthrange(year + 1900, month)[1] # unpack the date pattern octet string if sys.version_info[0] == 2: weeknday_unpacked = [ord(c) for c in weeknday] elif sys.version_info[0] == 3: weeknday_unpacked = [c for c in weeknday] else: raise NotImplementedError("match_weeknday requires Python 2.x or 3.x") month_p, week_of_month_p, day_of_week_p = weeknday_unpacked # check the month if month_p == 255: # any month pass elif month_p == 13: # odd months if (month % 2) == 0: return False elif month_p == 14: # even months if (month % 2) == 1: return False elif month != month_p: # specific month return False # check the week of the month if week_of_month_p == 255: # any week pass elif week_of_month_p == 1: # days numbered 1-7 if (day > 7): return False elif week_of_month_p == 2: # days numbered 8-14 if (day < 8) or (day > 14): return False elif week_of_month_p == 3: # days numbered 15-21 if (day < 15) or (day > 21): return False elif week_of_month_p == 4: # days numbered 22-28 if (day < 22) or (day > 28): return False elif week_of_month_p == 5: # days numbered 29-31 if (day < 29) or (day > 31): return False elif week_of_month_p == 6: # last 7 days of this month if (day < last_day - 6): return False elif week_of_month_p == 7: # any of the 7 days prior to the last 7 days of this month if (day < last_day - 13) or (day > last_day - 7): return False elif week_of_month_p == 8: # any of the 7 days prior to the last 14 days of this month if (day < last_day - 20) or (day > last_day - 14): return False elif week_of_month_p == 9: # any of the 7 days prior to the last 21 days of this month if (day < last_day - 27) or (day > last_day - 21): return False # check the day if day_of_week_p == 255: # any day pass elif day_of_week != day_of_week_p: # specific day return False # all tests pass return True
def test_monthly_rewards(): rewards = gs.get_monthly_rewards() now = datetime.now() assert len(rewards) == calendar.monthrange(now.year, now.month)[1]
# Agrego Path pathto = "/mnt/datos2/S2S_data/CNRM/v850/" # no further changes required from subprocess import call import calendar year_list = range(initial_year, final_year + 1) month_list = range(1, len(month_name_list) + 1) day_list = range(1, len(day_name_list) + 1) for dy in year_list: for dm in month_list: end_day = calendar.monthrange(dy, dm)[1] string = "" date_range = [ str(dy), month_name_list[dm - 1], day_name_list[0], "/to/", str(dy), month_name_list[dm - 1], day_name_list[len(day_list) - 1] ] file_name = [ pathto, "CNRM_", variable, "_", region, "_pf_reforecast_", str(dy), "_", month_name_list[dm - 1], ".grib" ] from ecmwfapi import ECMWFDataServer server = ECMWFDataServer() server.retrieve({ "class": "s2",
def budget_level(accounts=None, budget_value='0.0', year_to_date=True): """ Calculates how much is spent in the accounts provided. :param accounts: account walker parameters to calculate spending in. :param budget_value: budget value for the month :param year_to_date: should a year to date be calculated as well :return: dictionary containing: balance - the current balance for the month month - the month number daysInMonth - the number of days in the month today - current day in the month budgetValue - the maximum allowed to be spent in this month Optional values returned if year_to_date is true: yearlyBalance - the amount spent in these accounts this year daysInYear - the number of days in the current year currentYearDay - the current year day for this year """ accounts = accounts or [] budget_value = Decimal(budget_value or '0.0') accounts = parse_walker_parameters(accounts) budget_value = Decimal(budget_value) balance = Decimal('0.0') for account in account_walker(**accounts): split_list = get_splits(account, PeriodStart.this_month.date, PeriodEnd.today.date, debit=False) for split in split_list: balance += split.value data_payload = { 'balance': balance, 'month': PeriodEnd.today.date.month, 'daysInMonth': monthrange(PeriodEnd.today.date.year, PeriodEnd.today.date.month)[1], 'today': PeriodEnd.today.date.day, 'budgetValue': budget_value } if year_to_date: yearly_balance = Decimal('0.0') for account in account_walker(**accounts): split_list = get_splits(account, PeriodStart.this_year.date, PeriodEnd.today.date, debit=False) for split in split_list: yearly_balance += split.value today = PeriodStart.today.date data_payload.update({ 'yearlyBalance': yearly_balance, 'daysInYear': date(today.year, 12, 31).timetuple().tm_yday, 'currentYearDay': today.timetuple().tm_yday }) return data_payload
def reset_points_to_give(server): users = server.members response = 'The following users have been given new points to use:' new_points_given = False for user in users: user_points_left = 0 debug.debug(debug.D_INFO, 'Checking ' + str(user.name) + '...') try: user_points_left = storage.get_user_attribute( server.id, user.id, 'available_pearl_points') debug.debug(debug.D_INFO, str(user_points_left) + ' points left.') if user_points_left < pointToGiveCap: give = user_points_left + dailyPoints debug.debug(debug.D_INFO, 'Giving ' + str(dailyPoints) + ' point(s).') storage.set_user_attribute(server.id, user.id, 'available_pearl_points', give) response = '{}||{}'.format(response, user.mention) new_points_given = True except KeyError as e: debug.debug(debug.D_INFO, 'Skipping Ana...') # await client.send_message(server, response) debug.debug(debug.D_INFO, 'Points to spend have been reset') x = datetime.today() # today if datetime.now().hour < 17: y = x.replace(hour=17, minute=0, second=0, microsecond=0) # today at 5pm else: if x.day + 1 <= calendar.monthrange(x.year, x.month)[1]: y = x.replace(day=x.day + 1, hour=17, minute=0, second=0, microsecond=0) # tomorrow at 5pm else: if x.month + 1 <= 12: # first day of next month at 5pm y = x.replace(month=x.month + 1, day=1, hour=17, minute=0, second=0, microsecond=0) else: y = x.replace(year=x.year + 1, month=1, day=1, hour=17, minute=0, second=0, microsecond=0) delta_t = y - x # time between now and next reset secs = delta_t.seconds + 1 # t = Timer(secs, resetPointsToGive(server)) storage.set_server_attribute(server.id, 'next_pearl_point_reset_datetime', y) if not new_points_given: response = strings.no_players() return response
log = open(base_url + "cronjob/python/Loan/log/exportDailyPayment_log.txt","a") try: data = [] insertData = [] resultData = [] errorData = [] today = date.today() # today = datetime.strptime('13/02/2020', "%d/%m/%Y").date() day = today.day month = today.month year = today.year weekday = today.weekday() lastDayOfMonth = calendar.monthrange(year, month)[1] todayString = today.strftime("%d/%m/%Y") todayTimeStamp = int(time.mktime(time.strptime(str(todayString + " 00:00:00"), "%d/%m/%Y %H:%M:%S"))) startMonth = int(time.mktime(time.strptime(str('01/' + str(month) + '/' + str(year) + " 00:00:00"), "%d/%m/%Y %H:%M:%S"))) endMonth = int(time.mktime(time.strptime(str(str(lastDayOfMonth) + '/' + str(month) + '/' + str(year) + " 23:59:59"), "%d/%m/%Y %H:%M:%S"))) holidayOfMonth = mongodb.get(MONGO_COLLECTION=common.getSubUser(subUserType, 'Report_off_sys')) listHoliday = map(lambda offDateRow: {offDateRow['off_date']}, holidayOfMonth) if todayTimeStamp in listHoliday: sys.exit() yesterday = today - timedelta(days=1) yesterdayString = yesterday.strftime("%d/%m/%Y")
import datetime import calendar import json import sys import os import dotenv import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText this_dir = os.path.dirname(os.path.abspath(__file__)) + '/' # Get number of days today = datetime.date.today() days_in_this_month = calendar.monthrange(today.year, today.month)[1] today = today.day - 1 # Fetch people people_raw = open(this_dir + 'people.json').read() people_parsed = json.loads(people_raw) people_parsed = people_parsed['people'] people_parsed = [p.encode('utf-8') for p in people_parsed] # Find people to reconnect with today people = [] i = 0 while True: try: person = people_parsed[today + (i * days_in_this_month)] people.append(person) i = i + 1
spark = SparkSession.builder \ .appName('RLab_ID_Project___Extract_Valid_Phones') \ .config(conf=sparkConf) \ .enableHiveSupport() \ .getOrCreate() sc = spark.sparkContext sc.setLogLevel('ERROR') print('====> Parsing local arguments') parser = argparse.ArgumentParser() parser.add_argument('--query_month', type=str, help='The format should be YYYYmm') args = parser.parse_args() month_end = str( monthrange(int(args.query_month[:4]), int(args.query_month[4:6]))[1]) data_date = args.query_month + month_end start_time = time.mktime( datetime.strptime('2016-01-01', '%Y-%m-%d').timetuple()) end_time = time.mktime( datetime.strptime('{} 23:59:59'.format(data_date), '%Y%m%d %H:%M:%S').timetuple()) print('====> Start computation') pairs = getAndroidPairs(spark, data_date) devices = getActiveAndroids(spark, data_date) ill_devices = getAbnormalAndroids(spark, data_date) devices = devices.join(ill_devices, on='imei', how='left_outer').where( F.isnull(F.col('flag'))).select('imei') phones = pairs.join(devices, on='imei', how='inner').select('phone_salt').distinct()
stdmeridian = 105 east_wall_normal_from_north = 90 south_wall_normal_from_north = 180 west_wall_normal_from_north = 270 with open('/tmp/eplus_validation_location.csv', 'w') as csvfile: mywriter = csv.writer(csvfile) mywriter.writerow([ 'Hour', 'Hour Angle', 'Solar Altitude', 'Solar Azimuth', 'Cos East Wall Theta', 'Cos South Wall Theta', 'Cos West Wall Theta' ]) for month in range(1, 3): # just january and february thisLat = getLat(month) thisLong = getLong(month) for day in range(1, monthrange(2011, month)[1] + 1): # just make sure it isn't a leap year for hour in range( 0, 24 ): # gives zero-based hours as expected in the datetime constructor x = hour dt = datetime(2011, month, day, hour, 30, 00) thour = solar.hourAngle(dt, False, thisLong, stdmeridian).degrees altitude = solar.altitudeAngle(dt, False, thisLong, stdmeridian, thisLat).degrees azimuth = solar.solarAzimuthAngle(dt, False, thisLong, stdmeridian, thisLat).degrees east_theta = solar.solarAngleOfIncidence( dt, False, thisLong, stdmeridian, thisLat, east_wall_normal_from_north).radians
def daysinmonth(self): self.check_ini_n_end_dates_n_raise_if_consistent() return calendar.monthrange(self.end_timerange_date.year, self.end_timerange_date.month)[1]
def check_trigger(self, date_tuple, utc_offset=0): """ Returns boolean indicating if the trigger is active at the given time. The date tuple should be in the local time. Unless periodicities are used, utc_offset does not need to be specified. If periodicities are used, specifically in the hour and minutes fields, it is crucial that the utc_offset is specified. """ year, month, day, hour, mins = date_tuple given_date = datetime.date(year, month, day) zeroday = datetime.date(*self.epoch[:3]) last_dom = calendar.monthrange(year, month)[-1] dom_matched = True # In calendar and datetime.date.weekday, Monday = 0 given_dow = (datetime.date.weekday(given_date) + 1) % 7 first_dow = (given_dow + 1 - day) % 7 # Figure out how much time has passed from the epoch to the given date utc_diff = utc_offset - self.epoch[5] mod_delta_yrs = year - self.epoch[0] mod_delta_mon = month - self.epoch[1] + mod_delta_yrs * 12 mod_delta_day = (given_date - zeroday).days mod_delta_hrs = hour - self.epoch[3] + mod_delta_day * 24 + utc_diff mod_delta_min = mins - self.epoch[4] + mod_delta_hrs * 60 # Makes iterating through like components easier. quintuple = zip( (mins, hour, day, month, given_dow), self.numerical_tab, self.string_tab, (mod_delta_min, mod_delta_hrs, mod_delta_day, mod_delta_mon, mod_delta_day), FIELD_RANGES) for value, valid_values, field_str, delta_t, field_type in quintuple: # All valid, static values for the fields are stored in sets if value in valid_values: continue # The following for loop implements the logic for context # sensitive and epoch sensitive constraints. break statements, # which are executed when a match is found, lead to a continue # in the outer loop. If there are no matches found, the given date # does not match expression constraints, so the function returns # False as seen at the end of this for...else... construct. for cron_atom in field_str.split(','): if cron_atom[0] == '%': if not(delta_t % int(cron_atom[1:])): break elif field_type == DAYS_OF_WEEK and '#' in cron_atom: D, N = int(cron_atom[0]), int(cron_atom[2]) # Computes Nth occurence of D day of the week if (((D - first_dow) % 7) + 1 + 7 * (N - 1)) == day: break elif field_type == DAYS_OF_MONTH and cron_atom[-1] == 'W': target = min(int(cron_atom[:-1]), last_dom) lands_on = (first_dow + target - 1) % 7 if lands_on == 0: # Shift from Sun. to Mon. unless Mon. is next month target += 1 if target < last_dom else -2 elif lands_on == 6: # Shift from Sat. to Fri. unless Fri. in prior month target += -1 if target > 1 else 2 # Break if the day is correct, and target is a weekday if target == day and (first_dow + target - 7) % 7 > 1: break elif field_type in L_FIELDS and cron_atom.endswith('L'): # In dom field, L means the last day of the month target = last_dom if field_type == DAYS_OF_WEEK: # Calculates the last occurence of given day of week desired_dow = int(cron_atom[:-1]) target = (((desired_dow - first_dow) % 7) + 29) target -= 7 if target > last_dom else 0 if target == day: break else: # See 2010.11.15 of CHANGELOG if field_type == DAYS_OF_MONTH and self.string_tab[4] != '*': dom_matched = False continue elif field_type == DAYS_OF_WEEK and self.string_tab[2] != '*': # If we got here, then days of months validated so it does # not matter that days of the week failed. return dom_matched # None of the expressions matched which means this field fails return False # Arriving at this point means the date landed within the constraints # of all fields; the associated trigger should be fired. return True
#!/usr/bin/env python """ Created by howie.hu at 2019/4/19. """ import calendar import datetime from src.payment_schedule import PaymentSchedule class MonthlySchedule(PaymentSchedule): def is_pay_day(self, date: datetime.date): return calendar.monthrange(date.year, date.month)[1] == date.day def get_pay_period_start_date(self, pay_date: datetime.date): return pay_date.replace(day=1) if __name__ == '__main__': date = datetime.date(2019, 4, 22) print( calendar.monthrange( datetime.date(2019, 4, 22).year, datetime.date(2019, 4, 22).month)[1]) date = date.replace(day=1) print(date)
def __init__( self, montant_ini, monthrefdate, restart_timerange_date, # not to be confused with restart_mora_date end_timerange_date, # ie restart_mora_date is end_timerange_date + 1 day interest_rate, corrmonet_in_month, paid_amount=None, finevalue=None, monthseqnumber=1, contract_id=None): ''' Dynamic properties, ie derived fields, depend on other (original) fields (above) uptodate restart_mora_date was_fine_applied daysinmonth increaseamount updatedvalue balance self.uptodate => the same as end_timerange_date self.restart_mora_date => day after end_timerange_date self.was_fine_applied => if finevalue is not None, was_fine_applied is True; False otherwise self.daysinmonth => it calendar.monthrange(end_timerange_date)[1] (ie, total days in a month) of M+1 OBS.: end_timerange_date AND restart_timerange_date MUST ALWAYS BE IN THE SAME MONTH/YEAR otherwise, an exception will be raised self.increaseamount => it's the interest plus corr.monet. applied to debt (it does not include fine) self.updatedvalue => it's debt plus increaseamount (as above, it also does not include fine) self.balance => it's the net result of bill minus payment and possibly financial increases if payment is late balance is also called forwardvalue, for, when it's not zero, it becomes either previousdebts or cred_amount in the following bill. ''' self.montant_ini = montant_ini monthrefdate = treat_date(monthrefdate) self.monthrefdate = monthrefdate # this is never changed across an Amount Increase Trail list that shows the updating of a debt_account according to late payments! self.monthseqnumber = monthseqnumber self.contract_id = contract_id restart_timerange_date = treat_date(restart_timerange_date) self.restart_timerange_date = restart_timerange_date end_timerange_date = treat_date(end_timerange_date) self.end_timerange_date = end_timerange_date self.interest_rate = interest_rate self.corrmonet_in_month = corrmonet_in_month self.paid_amount = paid_amount # if not None, end_timerange_date equals semantically paydate self.finevalue = finevalue if self.restart_timerange_date is None: self.restart_timerange_date = self.monthrefdate + relativedelta( months=+1) if self.end_timerange_date is None: year = self.restart_timerange_date.year month = self.restart_timerange_date.month lastdayinmonth = calendar.monthrange(year, month)[1] self.end_timerange_date = self.restart_timerange_date.replace( day=lastdayinmonth) self.check_ini_n_end_dates_n_raise_if_consistent()
def get_last_day_of_prev_month(timezone=None): prev_month = current_time(timezone).replace(months=-1) return arrow.get(prev_month.year, prev_month.month, monthrange(prev_month.year, prev_month.month)[1])
def is_pay_day(self, date: datetime.date): return calendar.monthrange(date.year, date.month)[1] == date.day
def next_month(d): days_in_month = calendar.monthrange(d.year, d.month)[1] last = d.replace(day=days_in_month) n_month = last + timedelta(days=1) month = 'month=' + str(n_month.year) + '-' + str(n_month.month) return month
def uploadImage(self, image): """ Upload a single image. Returns the photoid, or None on failure. """ folderTag = image[len(IMAGE_DIR):] if self.uploaded.has_key(folderTag): stats = os.stat(image) logging.debug('The file %s already exists: mtime=%d, size=%d', image, stats.st_mtime, stats.st_size) data = self.uploaded[folderTag] if not isinstance(data, tuple): logging.error( 'Should not have non-tuple data but continuing in any case' ) self.uploaded[folderTag] = (data, stats.st_mtime, stats.st_size) return None else: photo_id = data[0] mtime = data[1] filesize = data[2] if mtime != stats.st_mtime or filesize != stats.st_size: logging.info('File has changed since previous time') logging.info('Removing %s from Flickr before updating', data[0]) photo = flickr.Photo(data[0]) try: photo.delete() del self.uploaded[folderTag] del self.uploaded[photo_id] except flickr.FlickrError: logging.info('File does not exist, adding') else: return None try: logging.debug("Getting EXIF for %s", image) f = open(image, 'rb') try: exiftags = exifread.process_file(f) except MemoryError: exiftags = {} f.close() #print exiftags[XPKEYWORDS] #print folderTag # make one tag equal to original file path with spaces replaced by # # and start it with # (for easier recognition) since space is # used as TAG separator by flickr # this is needed for later syncing flickr with folders # look for / \ _ . and replace them with SPACE to make real Tags realTags = re.sub(r'[/\\_.]', ' ', os.path.dirname(folderTag)).strip() if configdict.get('full_folder_tags', 'false').startswith('true'): realTags = os.path.dirname(folderTag).split(os.sep) realTags = (' '.join('"' + item + '"' for item in realTags)) picTags = '"#' + folderTag + '" ' + realTags #check if we need to override photo dates if configdict.get('override_dates', '0') == '1': dateTaken = datePosted = '' dateTakenGranularity = configdict.get('date_taken_granularity', '0') #fixed take date if configdict.get('date_taken_type', '0') == '2': datePosted = configdict.get('date_posted_fixed', '') #fixed post date if configdict.get('date_posted_type', '0') == '2': datePosted = configdict.get('date_posted_fixed', '') #Use year and month from config ini, then calculate end of month (note: Flickr does not accept future dates. You'll get current date maximum) if configdict.get('date_posted_granularity', '0') == '4': datePostedY = int( datetime.fromtimestamp(datePosted).strftime("%Y")) datePostedM = int( datetime.fromtimestamp(datePosted).strftime("%m")) datePostedD = calendar.monthrange( datePostedY, datePostedM)[1] datePosted = int( (datetime(datePostedY, datePostedM, datePostedD, 23, 59, 59) - datetime(1970, 1, 1)).total_seconds()) #Use year from config ini, then calculate end of year (note: Flickr does not accept future dates. You'll get current date maximum) if configdict.get('date_posted_granularity', '0') == '6': datePostedY = int( datetime.fromtimestamp(datePosted).strftime("%Y")) datePosted = int( (datetime(datePostedY, 12, 31, 23, 59, 59) - datetime(1970, 1, 1)).total_seconds()) #Convert timestamp to GMT zone dateZone = configdict.get('date_posted_utc', '0') if dateZone != '0': datePosted = datePosted - int(dateZone) * 3600 if exiftags == {}: logging.debug('NO_EXIF_HEADER for %s', image) else: if configdict.get('override_dates', '0') == '1': if 'EXIF DateTimeDigitized' in exiftags: dateExif = str(exiftags['EXIF DateTimeDigitized']) dateExif = dateExif[0:10].replace(':', '-') + dateExif[10:] dateUnix = int((datetime( int(dateExif[0:4]), int(dateExif[5:7]), int(dateExif[8:10]), int(dateExif[11:13]), int(dateExif[14:16]), int(dateExif[17:19])) - datetime(1970, 1, 1)).total_seconds()) if configdict.get('date_taken_type', '0') == '1': dateTaken = dateExif if configdict.get('date_posted_type', '0') == '1': datePosted = dateUnix #Use year and month from dateExif, then calculate end of month (note: Flickr does not accept future dates. You'll get current date maximum) if configdict.get('date_posted_granularity', '0') == '4': datePostedY = int( datetime.fromtimestamp( datePosted).strftime("%Y")) datePostedM = int( datetime.fromtimestamp( datePosted).strftime("%m")) datePostedD = calendar.monthrange( datePostedY, datePostedM)[1] datePosted = int( (datetime(datePostedY, datePostedM, datePostedD, 23, 59, 59) - datetime(1970, 1, 1)).total_seconds()) #Use year from dateExif, then calculate end of year (note: Flickr does not accept future dates. You'll get current date maximum) if configdict.get('date_posted_granularity', '0') == '6': datePostedY = int( datetime.fromtimestamp( datePosted).strftime("%Y")) datePosted = int(( datetime(datePostedY, 12, 31, 23, 59, 59) - datetime(1970, 1, 1)).total_seconds()) #Convert timestamp to GMT zone dateZone = configdict.get('date_posted_utc', '0') if dateZone != '0': datePosted = datePosted - int(dateZone) * 3600 # look for additional tags in EXIF to tag picture with if XPKEYWORDS in exiftags: printable = exiftags[XPKEYWORDS].printable if len(printable) > 4: try: exifstring = exifread.make_string(eval(printable)) picTags += exifstring.replace(';', ' ') except: logging.exception( "Skipping unexpected EXIF data in %s", image) picTags = picTags.strip() logging.info("Uploading image %s with tags %s", image, picTags) photo = ('photo', image, open(image, 'rb').read()) d = { api.token: str(self.token), api.perms: str(self.perms), "tags": str(picTags), "hidden": str(FLICKR["hidden"]), "is_public": str(FLICKR["is_public"]), "is_friend": str(FLICKR["is_friend"]), "is_family": str(FLICKR["is_family"]) } sig = signCall(d) d[api.sig] = sig d[api.key] = FLICKR[api.key] url = buildRequest(api.upload, d, (photo, )) res = getResponse(url) if isGood(res): logging.debug("successful.") photoid = str(res.photoid.text) self.logUpload(photoid, folderTag, image) if configdict.get('override_dates', '0') == '1': self.overrideDates(image, photoid, datePosted, dateTaken, dateTakenGranularity) return photoid else: print "problem.." reportError(res) except KeyboardInterrupt: logging.debug("Keyboard interrupt seen, abandon uploads") print "Stopping uploads..." self.abandonUploads = True return None except: logging.exception("Upload failed %s", image) return None
def display_next(self): view = self.current_view view.set_value() self.set_cursor(reset_view=False) if view.view_type == 'tree' and len(self.group): start, end = view.treeview.get_visible_range() vadjustment = view.treeview.get_vadjustment() vadjustment.value = min( vadjustment.value + vadjustment.page_increment, vadjustment.get_upper()) model = view.treeview.get_model() iter_ = model.get_iter(end) self.current_record = model.get_value(iter_, 0) elif (view.view_type == 'form' and self.current_record and self.current_record.group): group = self.current_record.group record = self.current_record while group: children = record.children_group(view.children_field) if children: record = children[0] break idx = group.index(record) + 1 if idx < len(group): record = group[idx] break parent = record.parent if not parent or record.model_name != parent.model_name: break next = parent.next.get(id(parent.group)) while not next: parent = parent.parent if not parent: break next = parent.next.get(id(parent.group)) if not next: break record = next break self.current_record = record elif view.view_type == 'calendar': record = self.current_record goocalendar = view.widgets['goocalendar'] date = goocalendar.selected_date year = date.year month = date.month start = datetime.datetime(year, month, 1) nb_days = calendar.monthrange(year, month)[1] delta = datetime.timedelta(days=nb_days) end = start + delta events = goocalendar.event_store.get_events(start, end) events.sort() if not record: self.current_record = len(events) and events[0].record else: for idx, event in enumerate(events): if event.record == record: next_id = idx + 1 if next_id < len(events): self.current_record = events[next_id].record break else: self.current_record = self.group[0] if len(self.group) else None self.set_cursor(reset_view=False) view.display()
sub = r.get_subreddit('findareddit') conn = sqlite3.connect('c:\\users\\caldw\\desktop\\far_analytics.db') c = conn.cursor() #TODO delete this c.execute( "CREATE TABLE IF NOT EXISTS mentions (subreddit text, count integer)") conn.commit() gen_log("Starting ......................") #start time magic year = time.gmtime().tm_year mon = time.gmtime().tm_mon if mon == 1: mon = 13 year = year - 1 days_last_month = calendar.monthrange(year, mon - 1)[1] seconds_last_month = 60 * 60 * 24 * days_last_month last_month_epoch = calendar.timegm( (year, mon - 1, days_last_month + 1, 0, 0, 0)) #end time magic lowest = last_month_epoch - seconds_last_month print lowest print last_month_epoch results = praw.helpers.submissions_between(r, sub, lowest_timestamp=lowest, highest_timestamp=last_month_epoch)
def add_months(source_date, months): month = source_date.month - 1 + months year = source_date.year + month // 12 month = month % 12 + 1 day = min(source_date.day, calendar.monthrange(year, month)[1]) return datetime.date(year, month, day)
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 18:55:59 2020 @author: kimyongkuk @title:calendar """ import calendar dayString = ("월", "화", "수", "목", "금", "토", "일") calendar.setfirstweekday(calendar.SUNDAY) print(calendar.calendar(2020)) print(calendar.month(2020, 4)) cald = calendar.monthrange(2020, 4) print(cald)