def monthly(from_date, to_date): from_date = from_date.replace(day=1) to_date = to_date.replace(day=1) + monthdelta.MonthDelta(1) months = [] tmpdate = datetime.date(from_date.year, from_date.month, from_date.day) while tmpdate < to_date: months.append(datetime.date(tmpdate.year, tmpdate.month, 1)) tmpdate += monthdelta.MonthDelta(1) cats = db.session.query(Category).all() catids = dict([(c.id, c.name) for c in cats]) keys = [m.strftime('%Y-%m') for m in months] ts = db.session.query(Transaction)\ .filter(Transaction.bdate>=from_date, Transaction.bdate<to_date) cat_keys = {} results = {} for t in ts: if t.category.id not in cat_keys: cat_keys[t.category.id] = [t.category.id] tmp = t.category.parent while tmp.name != 'top': cat_keys[t.category.id].append(tmp.id) tmp = tmp.parent cat_keys[t.category.id].append(tmp.id) for cid in cat_keys[t.category.id]: results[cid] = results.get(cid) or dict( [(k, []) for k in keys + ['yearly']]) if t.yearly: results[cid]['yearly'].append(t.amount) else: results[cid][t.bdate.strftime('%Y-%m')].append(t.amount) table = { 'headings': ['category', 'average'] + keys[::-1] + ['yearly', 'total'], 'rows': [] } top = db.session.query(Category).filter( Category.name == 'transactions').first() for cat in [top] + allChildren(top): cols = [(sum(results.get(cat.id, { k: [] }).get(k, []), 0.0), k) for k in keys[::-1] + ['yearly']] table['rows'].append({ 'category': cat, 'data': cols[:-1], 'yearly': cols[-1][0], 'total': sum([c[0] for c in cols]), 'average': "%.2f" % (sum([c[0] for c in cols[:-1]]) / (len(cols) - 1)), }) return table
def DateFwdAdj(dc, startDate, period, adj='F'): p = period[-1].upper() n = int(period[0:-1]) if p == 'D': d = startDate + datetime.timedelta(days=n) elif p == 'W': d = startDate + datetime.timedelta(weeks=n) elif p == 'M': d = startDate + monthdelta.MonthDelta(n) elif p == 'Y': d = startDate + monthdelta.MonthDelta(12 * n) else: return None return DateAdj(dc, d, adj)
def create_mort_schedule(): schs = [ 414.40, 415.91, 417.43, 418.95, 420.48, 422.01, 423.55, 425.09, 426.64, 428.2, 429.76, 431.33, 432.90, 434.48, 436.06, 437.65, ] # md = MonthDelta(1) d = datetime.date(2012, 1, 1) for s in schs: db.session.add( MortgageSchedule(d, s) ) d = d + monthdelta.MonthDelta(1)
def get_queryset(self): dates = {} month = int(self.kwargs.get('month', timezone.now().month)) year = int(self.kwargs.get('year', timezone.now().year)) # don't show last nights events that are technically today date_range_start = timezone.make_aware( timezone.datetime(year, month, 1, hour=10), timezone.get_default_timezone()) self.date_start = date_range_start date_range_end = date_range_start + monthdelta.MonthDelta(1) events = Event.objects.exclude(recordings=None).filter( start__range=(date_range_start, date_range_end)).order_by('start') if not self.request.user.is_staff: events = events.exclude(state=Event.STATUS.Draft) events = events.annotate(product_count=Count('products')).extra( select={ 'video_count': "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE " "events_recording.event_id = events_event. ID AND " "events_recording.media_file_id = multimedia_mediafile. ID AND " " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'" " GROUP BY events_event.id", 'audio_count': "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE " "events_recording.event_id = events_event. ID AND " "events_recording.media_file_id = multimedia_mediafile. ID AND " " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'" " GROUP BY events_event.id", }) for k, g in groupby(events, lambda e: e.listing_date()): dates[k] = list(g) sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0])).items() return sorted_dates
def cashflow(self, start, end, days): cur = self.start delta = 0 while (cur <= end): if cur >= start: delta += self.amount cur += monthdelta.MonthDelta(1) return delta
def cash_monthly_summary(self, start, end): start_date = parse_date(start) cur_date = parse_date(start) end_date = parse_date(end) while cur_date <= end_date: print(cur_date, self.cash_at_date_internal(start_date, cur_date)) cur_date += monthdelta.MonthDelta(1) if self.verbose: print()
def getDataMonthly(startYear,startMonth,endYear,endMonth,logicalSensors,outputDir): #iterate through each month () for dt in rrule.rrule(rrule.MONTHLY, dtstart=datetime(startYear,startMonth,1,0,0,0), until=datetime(endYear,endMonth,1,1,1)): #starting time (example 2014-01-01 00:00:00) startDate = dt endDate = dt+monthdelta.MonthDelta(1)- timedelta(minutes=1) startTime = getUTCTimestamp(startDate) #ending time (example 2014-01-31 23:59:00) endTime = getUTCTimestamp(endDate) #for each sensor get the data for the month print "Grabbing and dumping all sensor data for month "+str(startDate.strftime("%B"))+' '+str(startDate.year) for sensor in logicalSensors: #get the number of results numResults = getNumberOfData(startTime,endTime,timeZoneUTC,sensor['Id'],sensor['Unit']['Id']) if numResults > 0: #get the data data = getData(startTime,endTime,timeZoneUTC,sensor['Id'],sensor['Unit']['Id'],totalResults=numResults) fileName = str(startDate.year)+'-'+str(startDate.month)+'-'+str(sensor['Id'])+'-'+str(sensor['Unit']['Id']) #dump the data to a file dumpData(outputDir,fileName,sensor,timeZoneUTC,data)
def subtract_months(self, months): return self.current_date_time - monthdelta.MonthDelta(months=months)