def test_get_leap_years(): empty = [] result = get_leap_years(empty) print_test('test_get_leap_years', result == []) d1LeapYear = dt.Date(1, 1, 2008) d2LeapYear = dt.Date(3, 23, 2000) d0NotLeapYear = dt.Date(3, 23, 2009) d1NotLeapYear = dt.Date(1, 1, 1582) d2NotLeapYear = dt.Date(3, 23, 1900) all_leap_years = [d1LeapYear, d2LeapYear] result = get_leap_years(all_leap_years) print_test('test_get_leap_years', result == [d1LeapYear, d2LeapYear]) no_leap_years = [d0NotLeapYear, d1NotLeapYear, d2NotLeapYear] result = get_leap_years(no_leap_years) print_test('test_get_leap_years', result == []) some_leap_years = [ d0NotLeapYear, d2LeapYear, d1NotLeapYear, d2NotLeapYear, d1LeapYear ] result = get_leap_years(some_leap_years) print_test('test_get_leap_years', result == [d2LeapYear, d1LeapYear])
def test_is_before(): d1a = dt.Date(3, 23, 2018) d1Same = dt.Date(3, 23, 2018) d1Before1a = dt.Date(3, 23, 2017) d2Before1a = dt.Date(2, 23, 2018) d3Before1a = dt.Date(3, 22, 2018) d1After1a = dt.Date(3, 24, 2018) d2After1a = dt.Date(4, 22, 2018) d3After1a = dt.Date(4, 22, 2019) d4After1a = dt.Date(2, 24, 2019) d5After1a = dt.Date(2, 21, 2019) print_test('test_is_before- different objects, equal dt.Date', not (d1Same.is_before(d1a))) print_test('test_is_before - different objects, equal dt.Date', not (d1a.is_before(d1Same))) print_test('test_is_before - year is before', d1Before1a.is_before(d1a)) print_test('test_is_before - month is before', d2Before1a.is_before(d1a)) print_test('test_is_before - day is before', d3Before1a.is_before(d1a)) print_test('test_is_before - day is after', not (d1After1a.is_before(d1a))) print_test('test_is_before - month is after', not (d2After1a.is_before(d1a))) print_test('test_is_before - year is after, day is not', not (d3After1a.is_before(d1a))) print_test('test_is_before - year is after, month is not', not (d4After1a.is_before(d1a))) print_test('test_is_before - year is after, month and day are not', not (d5After1a.is_before(d1a)))
class Event(): title = "" start = Date(0,0,0,0) #fix later about end = Date(0,0,0,0) def __init__(self, titleEvent, startDate, endDate): self.title = titleEvent self.start = startDate self.end = endDate
def collect(self,strategic = None ,statisticsProjectPath = None): """ 对于整体数据,缓存之前计算。对于指定策略,暂时只收集15日内数据,反映短期内变动情况。 收集统计数据 >> statistics.stock == testCase['stock'] >> statistics.collect() 收集指定策略统计数据 >> statistics.stock == testCase['stock'] >> statistics.collect(strategic = testCase['collectStrategic']) @param {list} strategic 符合策略的code list """ conf={} conf.update(self.conf) isCache = False data={} if strategic: #计算指定策略统计 allCode = strategic #符合指定策略的 code 可通过strategic[date][strategicName]读出 allDate = [] for i in range(0,conf.get("MIN_DATA_NUM",MIN_DATA_NUM)): date=Date.getDate(0-i,conf.get('date',Date.getDate())) allDate.append(date) else: #计算整体统计 isCache = True allDate = self.stock.allDate allCode = self.stock.allCode if isCache: #读取之前统计缓存 data = Reader.read(path = self.getDataPath(dataType = "cache")) for date in allDate: if date in data and date in allDate: allDate.remove(date) conf.update({ "date":self.date, "stock":self.stock, "allCode":allCode }) expression=Expression(conf) statisticsProjectPath = statisticsProjectPath or os.path.join(conf.get("SYS_HOME"),conf.get("STATISTICS_PROJECT_PATH")) expressions = expression.load(path = statisticsProjectPath) for date in allDate: result={} #初始化result变量,让result能在公式里直接使用,并且result[name]也能使用 for code in allCode: result[code]={} expression.execute(expression= conf.get("expressions",expressions), context = {"result":result,"date":date}) if not result: break; data[date]=result if isCache: Dumper.dump(path = self.getDataPath(dataType = "cache"),data =data) return data
def update(self): ''' This method updates the current instance of the catalog. Creates an instance of Date with the experts catalog header and updates it in 30 minutes then updates the experts catalog and gets the header to create the tasks catalog header changing the word 'Experts' to 'Schedule'. Finally it gets the experts catalog file name and sets it to the tasks catalog file name replacing the word 'experts' with 'schedule'. ''' newDate = Date(self.experts.header[1], self.experts.header[3]) newDate.update(30) self.experts.update(newDate) for line in self.experts.header: self.header.append(line) self.header[6] = 'Schedule:' self.fileName = self.experts.fileName.replace('experts', 'schedule')
def test_get_years(): empty = [] result = get_years(empty) print_test('test_get_years empty', result == []) d0 = dt.Date(2, 23, 2011) d1 = dt.Date(3, 23, 1900) d2 = dt.Date(3, 23, 2009) d3 = dt.Date(2, 23, 2010) dt.Dates4 = [d0, d1, d2, d3] result = get_years(dt.Dates4) print_test('test_get_years not empty', result == [2011, 1900, 2009, 2010])
def day_of_the_week(date): ddate = Date.Date() year, month, dayofm = utils.split_date_string(date) ddate.year = year ddate.month = month ddate.day = dayofm return ddate.weekday()
def load_data(attacks: []) -> int: try: with open('/home/tzdybel/PycharmProjects/projekt2/Project2/globalterrorismdb.csv', 'r', encoding="ISO-8859-1") as csvfile: print("Loading data...") reader = csv.reader(csvfile, delimiter=',') for row in reader: if row[3] == 'iday': continue try: attkres = ar.AttackResult(bool(row[26]), bool(row[27]), int(row[98]), int(row[101])) except ValueError: attkres = ar.AttackResult(bool(row[26]), bool(row[27]), 0, 0) date = d.Date(int(row[3]), int(row[2]), int(row[1])) place = p.Place(row[12], row[8], getTypeFromEnum(int(row[9]), p.Region)) attkdet = ad.AttackDetails(getTypeFromEnum(int(row[28]), ad.AttackType), getTypeFromEnum(int(row[34]), ad.TargetType), getTypeFromEnum(int(row[81]), ad.WeaponType), row[64]) attack = att.Attack(date, place, attkdet, attkres) attacks.append(attack) except FileNotFoundError: print("File name is invalid") # exit(1) print("Loaded " + len(attacks).__str__() + " records!") return len(attacks)
def fix_tracker_stats_per_day(tracker_uuid): date_from = get_tracker_date(tracker_uuid) date_to = Date.get_today_date_str() # delete stats r_serv_tracker.delete(f'tracker:stat:{tracker_uuid}') r_serv_tracker.hdel(f'tracker:{tracker_uuid}', 'first_seen') r_serv_tracker.hdel(f'tracker:{tracker_uuid}', 'last_seen') # create new stats for date_day in Date.substract_date(date_from, date_to): date_day = int(date_day) nb_items = r_serv_tracker.scard(f'tracker:item:{tracker_uuid}:{date_day}') if nb_items: r_serv_tracker.zincrby('tracker:stat:{}'.format(tracker_uuid), int(date_day), nb_items) # update first_seen/last_seen update_tracker_daterange(tracker_uuid, date_day)
def __init__(self): self.date = Date() self.number = None self.payee = None self.cleared = 0 self.comment = None self.memo = None self.amount = None
def prompt(): month = (int(input("enter month or enter 0 to quit"))) if (month == 0): return None else: day = int(input("Enter date:")) year = int(input("Enter the year ")) return Date(month, day, year)
def fix_tracker_item_link(tracker_uuid): date_from = get_tracker_first_seen(tracker_uuid) date_to = get_tracker_last_seen(tracker_uuid) if date_from and date_to: for date_day in Date.substract_date(date_from, date_to): l_items = r_serv_tracker.smembers(f'tracker:item:{tracker_uuid}:{date_day}') for item_id in l_items: r_serv_tracker.sadd(f'obj:trackers:item:{item_id}', tracker_uuid)
def get_tracker_sparkline(tracker_uuid, num_day=6): date_range_sparkline = Date.get_date_range(num_day) sparklines_value = [] for date_day in date_range_sparkline: nb_seen_this_day = r_serv_tracker.zscore(f'tracker:stat:{tracker_uuid}', int(date_day)) if nb_seen_this_day is None: nb_seen_this_day = 0 sparklines_value.append(int(nb_seen_this_day)) return sparklines_value
def loadDates(self): month = input("Please enter the starting month (i.e January): ") day = int(input("Please enter the starting day (i.e 25): ")) hour = int(input("Please enter the starting hour: ")) am = input(str(hour) + " AM or " + str(hour) + "PM? (am/pm) ") minute = int(input("Please enter the starting minute: ")) if (am.lower() == "pm"): hour += 12 self.date = Date.Date(month, day, hour, minute)
def sqlStringAndValue(self, val, attr, dbtype): if val == SYSDATE: return 'SYSDATE', _NO_VALUE if Date.isDateTime(val): val = _dateConvertToDB(val) if string.upper(dbtype) == "LONG RAW": val = dbiRaw(val) self.bvcount = self.bvcount + 1 return ':p%d' % self.bvcount, val
def performOn(self): ''' This method uses the date and the hour of the (self) client to create a Date object with the date and the hour when the task should be performed. Returns: Date -- The date and hour when the task should be performed. ''' return Date(self.date, self.hour)
def sqlStringAndValue(self, val, attr, dbtype): if val == SYSDATE: return 'NOW()', _NO_VALUE #return 'SYSDATE', _NO_VALUE if Date.isDateTime(val): val = _dateConvertToDB(val, dbtype) # if string.upper(dbtype) == "LONG RAW": # val = sapdbapi.dbi.dbiRaw(val) self.bvcount = self.bvcount + 1 return '?', val
def get_tracker_items_by_daterange(tracker_uuid, date_from, date_to): all_item_id = set() if date_from and date_to: l_date_match = r_serv_tracker.zrange(f'tracker:stat:{tracker_uuid}', 0, -1, withscores=True) if l_date_match: dict_date_match = dict(l_date_match) for date_day in Date.substract_date(date_from, date_to): if date_day in dict_date_match: all_item_id |= r_serv_tracker.smembers(f'tracker:item:{tracker_uuid}:{date_day}') return all_item_id
def __init__(self,conf={}): """ @param {list} conf["expression"] 要执行的表达式 @parma [date] conf['date'] 要处理的日期 @pram conf['project'] 要处理的project名。如果传入该参数,则处理该参数指定的project.否则处理expressionPath里所有的project @param conf['context'] exec执行公式时的环境变量 """ self.conf=conf self.code=None self.date=conf.get('date',Date.getDate()) self.stock=conf.get("stock",Stock.Stock(conf)) self.project=conf.get('project',[]) self.context=conf.get('context',{}) self.re={}
def typeCheckAndConvert(self, val, aname, attr): if _isDateKind(attr): if not Date.isDateTime(val) and not val == PyDBI.SYSDATE: raise TypeError,'trying to assign %s to %s and is not a date'%( val, aname) val = _dateConvertToDB(val) elif (_isNumber(attr) and not isinstance(val, types.FloatType) and not isinstance(val, types.IntType)): raise TypeError, ('trying to assign %s to %s and is not' ' a number') % (val, aname) elif _isString(attr) and not isinstance(val, types.StringType): raise TypeError, 'trying to assign %s to %s and is not a string'% ( val, aname) return val
def typeCheckAndConvert(self, val, aname, attr): #nulls always allowed (unless the db says no) if val is None: return val if _isDateKind(attr) and not (Date.isDateTime(val) or val is SYSDATE): raise TypeError,'trying to assign %s to %s and is not a date'%( val, aname) val = _dateConvertToDB(val) elif (_isNumber(attr) and not isinstance(val, types.FloatType) and not isinstance(val, types.IntType)): raise TypeError, ('trying to assign %s to %s and is not' ' a number') % (val, aname) elif _isString(attr) and not isinstance(val, types.StringType): raise TypeError, 'trying to assign %s to %s and is not a string'% ( val, aname) return val
def setdate(self,rest): self.date = Date(rest) return
def index(self,index): self.date=Date.getDate(index , self.date) return self
class Check: def __init__(self): self.date = Date() self.number = None self.payee = None self.cleared = 0 self.comment = None self.memo = None self.amount = None def __str__(self): str = "%10s " % self.date.formatUS() if self.number: str = str + "%5d " % self.number else: str = str + " " str = str + "%-20s " % string_limit(self.payee,20) if self.cleared: str = str + "x " else: str = str + " " if self.comment: str = str + "%-10s " % string_limit(self.comment,10) else: str = str + " " if self.memo: str = str + "%-10s " % string_limit(self.memo,10) else: str = str + " " str = str + "%8.2f " % self.amount return str def lb_repr(self): return str(self) def __cmp__(self,other): return cmp(self.date,other.date) def qif_repr(self): str = "D%s\n" % self.date.formatUS() str = str + "T%.2f\n" % self.amount if self.cleared: str = str + "Cx\n" else: str = str + "C*\n" if self.number: str = str + "N%d\n" % self.number str = str + "P%s\n" % self.payee if self.comment: str = str + "L%s\n" % self.comment if self.memo: str = str + "M%s\n" % self.memo str = str + "^\n" return str def setamount(self,rest): words = string.split(rest) # some broken qif files have numbers of the form: 1,839.41 amount = string.replace(words[0], ',', '') self.amount = float(amount) return def setdate(self,rest): self.date = Date(rest) return def setpayee(self,rest): self.payee = rest return def setcleared(self,rest): if rest[0] == "x": self.cleared = 1 else: self.cleared = 0 return def setnumber(self,rest): words = string.split(rest) if not words: self.number = 0 else: self.number = int(words[0]) return def setcomment(self,rest): self.comment = rest return def setmemo(self,rest): self.memo = rest return
def __init__(self,date = None ,conf={}): self.date = date or conf.get("date",Date.getDate()) self.data = conf.get("data",{}) self.cacheTotalStatistics = True #对统计所有日期是否使用之前统计数据 self.stock = conf.get("stock",Stock(conf)) self.conf = conf
from Date import * test_date = Date(22, 12, 2016) counter = 1 for i in range(0, 100, 1): test_date.add_days(1) print(test_date) print(counter) counter += 1
def main(): today = Date() print(today) today.setDate(4, 16, 2012) print(today) today.setDate(2,29,1997) print(today) print("Month = " + str(today.getMonth())) print("Day = " + str(today.getDay())) print("Year = " + str(today.getYear())) today.setDate(12, 8, 1200) print(today) today.setDate(13, 8, 2012) print(today)
def __init__(self,date=None,conf={}): self.conf = conf self.date = date or conf.get("date",Date.getDate()) self.data = conf.get("data",{}) self.stock = conf.get("stock",None)
allstocks=getListAllStocks(i,exchange) for idx,stock in enumerate(allstocks): if stock[1]>="A" and stock[1]<="Z": #debug condition dates=array([]) highs=array([]) lows=array([]) prices=array([]) volume=array([]) close=array([]) for year in range(2000,2014):#2000,2014 symbol=stock[1] #print symbol,exchange,year d,h,l,p,v,c=ss.getStock(symbol,exchange,year) firstday=Date.toDaniDate(str(year)+"-01-01") das=filter(lambda date: Date.laterThan(Date.toDaniDate(date[0]),firstday),zip(d,h,l,p,v,c)) try: d,h,l,p,v,c=zip(*das) except ValueError: dum=0 dates=hstack((dates,d)) highs=hstack((highs,h)) lows=hstack((lows,l)) prices=hstack((prices,p)) volume=hstack((volume,v)) close=hstack((close,c))