def date_from_meta(meta_tags: List[str], label: str) -> date: tag_arr = str_from_meta(meta_tags, label).split(": ") try: return date.strptime(tag_arr[1], "%m/%d/%Y") except: try: return date.strptime(tag_arr[1], "%b %d, %Y") except: return date.today()
def date_range(dt1, dt2): dt1 = date.strptime(dt1, '%Y%m%d') if not isinstance(dt1, date) else dt1 dt2 = date.strptime(dt2, '%Y%m%d') if not isinstance(dt2, date) else dt2 logger.debug("Generating date range between %s and %s", dt1, dt2) assert dt2 > dt1, 'Can not generate date range where the latter date (%s) is before the former date (%s)' % (dt2, dt1) for i in range((dt2 - dt1).days + 1): dt = dt1 + timedelta(i) yield dt
def standardize_job(self, job_dict): start_date = job_dict.get("start_date") or None if start_date: start_date = date.strptime(start_date, "%Y-%m-%d") or None end_date = job_dict.get("end_date") or None if end_date: end_date = date.strptime(end_date, "%Y-%m-%d") or None return dict(title=job_dict.get("title") or None, industry=job_dict.get("industry") or None, start_date=start_date, end_date=end_date)
def ImportDalumSkema( config, ConfigSet = "DalumSkema" ): ''' Retrieves events from dalum in the given interval. config needed 'offset', 'NumWeeks', 'BaseWeek' (using current year, 0 means current week), 'TeacherId' @param config: the configuration object @param ConfigSet: The sub configuration to use ''' now = date.today() # getting reference date BaseWeek = int(config.get( ConfigSet, 'BaseWeek' )) if BaseWeek == 0: BaseDate = now else: BaseDate = date.strptime("%s %s" % (now.year, BaseWeek, "%Y %W") ) # the week range WeekOffset = int( config.get( ConfigSet, 'Offset' ) ) WeekCount = int( config.get( ConfigSet, 'NumWeeks' ) ) StartDate = BaseDate + timedelta(weeks=WeekOffset) EndDate = BaseDate + timedelta(weeks=WeekOffset+WeekCount) if StartDate.year != EndDate.year: raise ValueError( "Data extraction across new year not implemented" ) WeekRange = range( StartDate.isocalendar()[1], EndDate.isocalendar()[1] ) # and extract stuff s = DalumSkemaScraper( int(config.get( ConfigSet, 'TeacherId' )), WeekRange ) s.ExtractAppointments( NonFatal = True ) Apps = s.GetAppointments() return Apps
def download(self, key, datarange, init_date = None, map_meaningful = None): # print('key', key) gc = gspread.login(self.user, self.password) if isinstance(init_date, date): pass elif isinstance(init_date, dict): init_date = datetime(tzinfo = TZI, **init_date).date() elif isinstance(init_date, str): init_date = date.strptime(init_date, "%d %b %y") # 26 nov 12 else: init_date = self._get_init_date(gc, key) def datasize(drange): start, end = drange.split(':') letters = lambda x, boo: ''.join([ z for z in x if z.isdigit()!=boo ]) start_letters = letters(start,1) start_digits = letters(start,0) end_letters = letters(end,1) end_digits = letters(end,0) col_names = list(map(str.strip,map(''.join,itertools.combinations_with_replacement(' ABCDEFGHIJKLMNOPQRSTUVWXYZ', 2))))[1:] x_size = col_names.index(end_letters) - col_names.index(start_letters) y_size = int(end_digits) - int(start_digits) return x_size + 1, y_size + 1 # +1 because bothe start and end index are part of the range # wks = gc.open("schedule").get_worksheet(1) wks = gc.open_by_key(key).get_worksheet(1) sheet_data = wks.range(datarange) # print('sheet data', sheet_data) results = self._parse_shifts(init_date, sheet_data, *datasize(datarange), map_meaningful=map_meaningful) return results
def load_movies(): """Load movies from u.item into database.""" Movie.query.delete() for row in open("seed_data/u.item"): row = row.rstrip().split("|") movie_id = row[0] title = row[1] released_at = row[2] imdb_url = row[4] title = re.sub(r" \(\d+\)$", "", title) if released_at: date_formatted_release = date.strptime(released_at, '%d-%b-%Y') else: date_formatted_release = None movie = Movie(movie_id=movie_id, title=title, released_at=date_formatted_release, imdb_url=imdb_url) db.session.add(movie) db.session.commit()
def _compute_date_due(self, cr, uid, ids, fields, arg, context=None): res = {} for loan in self.browse(cr, uid, ids, context=context): start_date = date.strptime(loan.date, DATE_FMT) due_date = start_date + timedelta(days=loan.duration) res[loan.id] = due_date.strftime(DATE_FMT) return res
def get_val_from_text(self, str_val, simple_field): """ Converts a text to it's corresponding value, of the type specified by the field_type property of the simple_field element. Returns None if the cast fails. """ ft = simple_field.field_type en = simple_field.english_notation try: if ft == FieldType.BOOLEAN: return_val = bool(str_val) elif ft == FieldType.BYTE: return_val = int(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.INT16: return_val = int(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.INT32: return_val = int(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.INT64: return_val = long(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.SINGLE: return_val = float(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.DOUBLE: return_val = float(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.DECIMAL: return_val = Decimal(self._replace_decimal_signs(str_val, en)) elif ft == FieldType.DATE: if len(simple_field.datetime_format) > 0: return_val = date.strptime(str_val, simple_field.datetime_format) else: return_val = date.strptime(str_val) elif ft == FieldType.TIME: if len(simple_field.datetime_format) > 0: return_val = time.strptime(str_val, simple_field.datetime_format) else: return_val = time.strptime(str_val) elif ft == FieldType.DATETIME: if len(simple_field.datetime_format) > 0: return_val = date.strptime(str_val, simple_field.datetime_format).date() else: return_val = date.strptime(str_val).date() elif ft == FieldType.STRING: return_val = str_val except: return_val = None return return_val
def _calculate_age(self, birthday): today = date.today() if birthday: _birth = date.strptime(birthday, '%Y-%m-%d') diff = today - _birth return int(diff.days / 365.2425) else: return False
def on_change_date_end(self, cr, uid, date_end, context=None): date_end = date.strptime(date_end, DATE_FMT) today = date.today() if date_end <= today: return { 'value': {'loan_duration': 0}, 'warning': { 'title': 'expired membership', 'message': 'This member membership has expired', }, }
def to_date(value, formatString='%Y/%M/%d'): if isinstance(value, date): return value if isinstance(value, datetime): return date(value.year, value.month, value.day) if isinstance(value, (QtCore.QDate, QtCore.QDateTime)): return date(value.year(), value.month(), value.day()) if isinstance(value, str): return date.strptime(obj, formatString) else: raise ValueError('to_date:invalid type <%s>' % str(type(value)))
def format_date(date, tag): if type(date) == 'str': date = date.strptime("%Y %m %d") else: date = date if tag == 'SHORT': date_new = date.strftime('%b %d') elif tag == 'HEADER': date_new = date.strftime('%A %d %b') elif tag == "SEARCH": date_new = date.strftime("%Y/%d/%m") return date_new
def on_change_date_end(self, cr, uid, date_end, context=None): date_end = date.strptime(date_end, DATE_FMT) today = date.today() if date_end <= today: return { 'value': { 'loan_duration': 0 }, 'warning': { 'title': 'expired membership', 'message': 'This member membership has expired', }, }
def vanityPageUpdateDate(self): '''Last time vanity page was updated''' value = self.context.getProperty('vanityPageUpdateDate', None) if value is None: return date.min elif isinstance(value, basestring): return date.strptime(value, '') elif isinstance(value, oldDateTime): dt = value.asdatetime() return date(dt.year, dt.month, dt.day) elif isinstance(value, datetime): return date(value.year, value.month, value.day) # Assume it's a date at this point return value
def choose_reservation_type(date_str): """Choose reservation type by date string in formats YYYY-mm-dd YYYY/mm/dd """ if date_str is None: return None try: date_str = date_str.replace('/', '-') selected_date = date.strptime(date_str, '%Y-%m-%d') return choose_reservation_type_by_date(selected_date) except: return None
def prepare_data(days='1', _date=None): vars = config() days = int(days) if not _date: dt = date.today() - timedelta(days=1) _date = dt.strftime('%Y-%m-%d') else: dt = date.strptime('%Y-%m-%d') make_dirs() et = dt + timedelta(days=-days) while dt>et: _date = dt.strftime('%Y-%m-%d') fn = os.path.join(vars['hk.data'], 'habakkuk-%s.json.gz'%_date) local('hadoop fs -copyFromLocal %s input'%fn) dt-=timedelta(days=1) local("hadoop fs -ls %(hk.input)s"%vars)
def transform_csv_cell_type(cell_str): try: return int(cell_str) except: pass try: return float(cell_str) except: pass try: return date.strptime(cell_str, "%Y-%m-%d") except: pass if cell_str == 'None': return None return cell_str
def _object_decode(self, obj): type = obj.get('__type__', None) typemap = { 'datetime': lambda x: datetime.strptime(x['__repr__'], "%Y-%m-%dT%H:%M:%S.%fZ" ), 'date': lambda x: date.strptime(x['__repr__'], "%Y-%m-%d"), 'time': lambda x: time.strptime(x['__repr__'], "%H:%M:%S.%fZ"), 'timedelta': lambda x: timedelta(seconds=x['__repr__']), 'decimal': lambda x: Decimal(x['__repr__']), None: lambda x: x } return typemap[type](obj)
def createRow(self): d = {} for _structType in sorted(self.schema.fields): # print "_structType=", _structType val = self.__dict__[_structType.name] # print "val=", val if _structType.dataType == StringType(): val = str(val) if val is not None else None # print "now String" elif _structType.dataType == IntegerType(): if val == "": val = None val = int(val) if val is not None else None # print "now Int", val, "name=", _structType.name elif _structType.dataType == TimestampType(): val = val elif _structType.dataType == DateType(): if isinstance(val, str): val = date.strptime(val, "%Y-%m-%d") elif isinstance(val, datetime): val = val.date() elif isinstance(val, date): pass else: raise Exception("cant convert to date:" + val) elif _structType.dataType == DoubleType(): val = float(val) elif _structType.dataType == ShortType(): val = int(val) elif _structType.dataType == ByteType(): val = int(val) elif _structType.dataType == BooleanType(): val = val else: print "TYPE NOT FOUND, " + str(_structType) + "now string?" d[_structType.name] = val # print "CONVERTED, d=", d return Row(**d)
def get_data(self, filename: str, show_plot: bool = False): dates = [] open_prices = [] close_prices = [] high_prices = [] low_prices = [] volume = [] with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) # skip first row for row in csvFileReader: date_time_obj = date.strptime(row[0], '%Y-%m-%d') dates.append((int)(date_time_obj.strftime("%Y%m%d"))) open_prices.append(float(row[1])) close_prices.append(float(row[4])) high_prices.append(float(row[2])) low_prices.append(float(row[3])) volume.append(int(row[6])) if show_plot: LR = lr.show_LR_plot(dates, open_prices) return dates, open_prices, close_prices, high_prices, low_prices, volume
def parsePriceVolume(jsonDump, source, sink, exchange): """Parse price / volume data for specific exchange & trading pair.""" rows = json.loads(jsonDump) data = [] for row in rows: datum = {} datum["source"] = source datum["sink"] = sink datum["exchange"] = exchange if len(row[0]) == 10: datum["date"] = date.strptime(row[0], "%Y-%m-%d") elif len(row[0]) == 13: datum["hour"] = datetime.strptime(row[0], "%Y-%m-%d %H") datum["price_low"] = row[1] datum["price_25th_percentile"] = row[2] datum["price_75th_percentile"] = row[3] datum["price_high"] = row[4] datum["price_median"] = row[5] datum["price_ema20"] = row[9] datum["volume"] = row[6] datum["field_7"] = row[7] datum["field_8"] = row[8] data.append(datum) return data
Stations = Base.classes.sta # Create our session (link) from Python to the DB session = Session(engine) ################################################# # Flask Setup ################################################# ################################################# # Flask Routes ################################################# calcs = session.query(Measurements.date, Measurements.tobs) records = [] for record in calcs: records.append(record[0]) # print(records) dater = date.strptime("12-20-2016", '%m-%d-%Y') print(type(dater)) # tmin = min(records) # tmax = max(records) # tavg = np.mean(records) # records_dict = { # "min_temp": tmin, # "max_temp": tmax, # "avg_temp": tavg # } # return jsonify(records_dict)
def __strToDate(str): d = date.strptime(str,'%b%y') return workingday.last(d.year, d.month)
def date_str_to_obj(date_str): date_obj = date.strptime(date_str, "%Y-%m-%d") return date_obj
args = parser.parse_args() if args.date is not None: transaction_date = args.date valid_transaction_date = None while valid_transaction_date is None: try: transaction_date = raw_input("No date specified. Please specifies a date [today]: ") if transaction_date == "": valid_transaction_date = date.today() else: valid_transaction_date = date.strptime(transaction_date, "%Y/%m/%d") except ValueError, e: print "Invalid date. Please enter a valid date: " payee = ask(args.payee, "No payee specified. Please specifies a payee []: ") if args.amount is not None: amount = args.amount else: amount = "" while amount == "": amount = raw_input("No amount specified. Please enter an amount: ") try: amount = Decimal(amount) except InvalidOperation, e: print "Invalid amount. Please entry a decimal value"
def to_python(self, value): if isinstance(value, six.string_types) and len(value) == 19: return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") elif isinstance(value, six.string_types) and len(value) == 10: return date.strptime(value, "%Y-%m-%d")
def upgrade(): for line in open("data/na_bills_19.txt", "r"): bill_raw = json.loads(line) validate(bill_raw) bill_id = bill_raw["bill_id"] name = bill_raw["title"] age = 19 proposed_date = bill_raw["proposed_date"] decision_date = bill_raw["decision_date"] is_processed = bill_raw["status"] == "처리" link_id = bill_raw["link_id"] sponsor = bill_raw["status_dict"]["접수"]["의안접수정보"][0]["제안자"] while isinstance(sponsor, list): sponsor = sponsor[0] status_ids = [bill_status_id(status) for status in bill_raw["statuses"]] status_id = bill_status_id(bill_raw["status_detail"]) op.execute( bill_t.insert().values( { "id": bill_id, "name": name, "age": age, "proposed_date": proposed_date, "decision_date": decision_date, "is_processed": is_processed, "link_id": link_id, "sponsor": sponsor, "status_ids": status_ids, "status_id": status_id, } ) ) for proposer in bill_raw["proposers"]: if proposer not in person_ids: try: person = guess_person(proposer) except Exception, e: person = None print proposer, e person_ids[proposer] = person.id if person else None person_id = person_ids[proposer] if person_id: op.execute(cosponsorship_t.insert().values({"person_id": person_id, "bill_id": bill_id})) for review_name, review_data in bill_raw["status_dict"].items(): dates = any_value_with_re(review_data, date_re) dates = [date.strptime(date_, "%Y-%m-%d") for date in dates] start_date = min(dates) if dates else None end_date = max(dates) if dates else None op.execute( bill_review_t.insert().values( { "name": review_name, "bill_id": bill_id, "start_date": start_date, "end_date": end_date, "data": json.dumps(review_data), } ) )
divmod(7, 3) max(list1) min(list1) b = 1.414435345 round(b, 1) sorted(list1, reverse=True) # a lot of things can learn about sort # math functions import math math.pi math.pow(2, 2) # date time functions from datetime import date today = date.today() print(today) date_format = '%d/%m/%Y' converted_date = date.strptime('19/9/2018', date_format) print(converted_date) my_birthday = date(1994, 8, 3) time_to_birthday = abs(my_birthday - today) import urllib.request import re url = "http://checkip.dyndns.org" request = urllib.request.urlopen(url).read().decode('utf-8') theIP = re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', request) print('Your IP Address is ', theIP[0])
'-': lambda l, r: float(l) - float(r), # ['-', 1, 2] '*': lambda l, r: float(l) * float(r), # ['*', 1, 2] '%': f_mod, # ['%', 14, 10] 'mod': f_mod, # ['mod', '@n', 10] '/': lambda l, r: (l * 1.0) / r, # ['/', 1, 2] '!': lambda expr: not expr, # ['!', ['true']] 'not': lambda val: not val, # ['not', ['true']] '&&': f_all, # ['&&', [], [], ...] 'and': f_all, # ['and', [], [], ...] '::': f_any, # ['::', [], [], ...] '||': f_any, 'or': f_any, # ['or', [], [], ...] 'if': lambda c, t, f: t if c else f,# ['if', 'cond', 'true', 'false'] 'true': lambda: True, # ['true'] 'false': lambda: False, # ['false'] 'date': lambda date: date.strptime(date, '%Y-%m-%d'),# ['date', '2010-01-01'] 'today': lambda: date.today(), # ['today'] 'time': lambda time: date.strptime(time, '%Y-%m-%d %H:%M:%S'), # ['time', '2010-01-01 10:10:05'] 'now': lambda: date.now(), # ['now'] 'append': lambda l, r: to_string(r) + to_string(l), # ['append', 'world', 'hello '] 'prepend': lambda l, r: to_string(l) + to_string(r), # ['prepend', 'hello ', 'world'] 'match': f_match, # ['match', /a/, 'abc'] 'in': in_f, # ['in', '1,2,3,5..10,20..24', '@n'] 'within': within_f, # ['within', '0..3', '@n'] 'replace': f_replace, 'count': len, # ['count', '@genders'] 'all': lambda of, value: all([el == value for el in of]), # ['all', '@genders', 'male'] 'any': lambda of, value: any([el == value for el in of]) # ['any', '@genders', 'female'] }
def from_iso_date(iso_date): """Convert an ISO date to a date object).""" return date.strptime(iso_date, ISO_8601_DATE_FMT)
def hiduke2yyyymmdd_sub(datestr): yyyymmdd_from = None yyyymmdd_to = None dfrom = None dto = None if datestr == None or (datestr and datestr.strip() == ""): return None, None datestr = datestr.strip() datestr = datestr.replace("[]??()()", "") # あいまい記号を削除 datestr = datestr.replace(" ", "") # 半角全角スペースを削除 datestr = datestr.translate(str.maketrans("1234567890", '1234567890')) # 全角数字を半角に変換 datestr = datestr.translate(str.maketrans("一二三四五六七八九〇元", '12345678901')) # 漢数字を半角数字に変換 datestr = datestr.upper() # アルファベット半角小文字を半角大文字に変換 datestr = datestr.translate(str.maketrans(".-", '//')) #print("datestr={0}".format(datestr)) gengou_label = datestr[0:2] gengou = next((filter(lambda x:x['key'] == gengou_label, DateHelper.GENGOUS)), None) m = REMatcher() if gengou: # 和暦 datestr = datestr.translate(str.maketrans("年月日", '///')) key = gengou['key'] if m.match("^({0})(\d{{1,2}})\/(\d{{1,2}})\/(\d{{1,2}})".format(key) , datestr): syyyy = DateHelper.wareki2yyyy(m.group(1), m.group(2)) dfrom = dto = Date(syyyy, int(re.group(3)), int(re.group(4))) elif m.match("^({0})(\d{{1,2}})\/(\d{{1,2}})".format(key), datestr): syyyy = DateHelper.wareki2yyyy(m.group(1), int(m.group(2))) dfrom = SimpleDate(syyyy, m.group(3)).to_date() dto = SimpleDate(syyyy, m.group(3)).end_of_month() elif m.match("^({0})(\d{{1,2}})".format(key), datestr): syyyy = DateHelper.wareki2yyyy(m.group(1), int(m.group(2))) dfrom = SimpleDate(syyyy).to_date() dto = SimpleDate(syyyy).end_of_year() else: dfrom = Date.strptime(gengou['from'], '%Y%m%d') dto = Date.strptime(gengou['to'], '%Y%m%d') # union if dfrom: yyyymmdd_from = dfrom.strftime("%Y%m%d") if dto: yyyymmdd_to = dto.strftime("%Y%m%d") elif m.match(r"^\d{4}", datestr): # 西暦 datestr = datestr.translate(str.maketrans("年月日", '///')) #print("datestr={0}".format(datestr)) if m.match(r"^(\d{4})\/(\d{1,2})\/(\d{1,2})", datestr): dfrom = dto = SimpleDate(m.group(1), m.group(2), m.group(3)).to_date() elif m.match(r"^(\d{4})\/(\d{1,2})", datestr): dfrom = SimpleDate(m.group(1), m.group(2)).to_date() dto = SimpleDate(m.group(1), m.group(2)).end_of_month() elif m.match(r"^(\d{4})", datestr): dfrom = SimpleDate(m.group(1)).to_date() dto = SimpleDate(m.group(1)).end_of_year() else: print("format error (3) #{datestr}") # union if dfrom: yyyymmdd_from = dfrom.strftime("%Y%m%d") if dto: yyyymmdd_to = dto.strftime("%Y%m%d") else: print("format error (1) #{datestr}") return yyyymmdd_from, yyyymmdd_to
def _parse_date_from_str(date_str): return date.strptime(date_str, DATE_FMT)
def __strToDate(str): d = date.strptime(str, '%b%y') return workingday.last(d.year, d.month)
def import_shipment_in(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for product supplier shipment') readertest = csv.DictReader(f) print(readertest.fieldnames) for row in readertest: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name'], row['stock.location_warehouse'], row['stock.location_from'], row['stock.location_to'], row['stock.move_effective_date'], row['stock.move_planned_date'], row['stock.move_unit_price'], row['stock.move_cost_price'], row['supplier']) f.seek(0) print('Start import') StockShipmentIn = Model.get('stock.shipment.in') duplicate = StockShipmentIn.find([('reference', '=', filename)]) if duplicate: print('Existing supplier shipment found: ' + str(duplicate[0].id) + ' - ' + filename) raise ValueError( 'Existing supplier shipment found with the same filename: ' + str(duplicate[0].id) + ' - ' + filename) else: stockshipmentin = StockShipmentIn() stockshipmentin.reference = filename Location = Model.get('stock.location') locationlist = Location.find([('id', '>', 0)]) Party = Model.get('party.party') supplier = Party.find([('name', '=', DEFAULT_PARTY_SUPPLIER)], limit=1) PartyAddress = Model.get('party.address') supplier_address = PartyAddress.find( [('party', '=', supplier[0].id)], limit=1) if row['stock.move_planned_date'] == 'today': planned_date = date.today() else: planned_date = date.strptime(row['stock.move_planned_date'], "%Y-%m-%dT") stockshipmentin.planned_date = planned_date if row['stock.move_effective_date'] == 'today': effective_date = date.today() else: effective_date = date.strptime( row['stock.move_effective_date'], "%Y-%m-%dT") stockshipmentin.effective_date = effective_date stockshipmentin.supplier = supplier[0] stockshipmentin.contact_address = supplier_address[0] stockshipmentin.warehouse = getLocation( locationlist, row['stock.location_warehouse']) stockshipmentin.save() ProductUOM = Model.get('product.uom') productUOMList = ProductUOM.find([('id', '>', 0)]) reader = csv.DictReader(f) moves = [] if stockshipmentin.id > 0: StockInventoryLine = Model.get('stock.inventory.line') stockinventoryline = StockInventoryLine() for row in reader: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name']) # internal SUP -> IN stockmove = stockinventoryline.moves.new() stockmove.shipment = stockshipmentin Product = Model.get('product.product') product = Product.find([('code', '=', row['code'])]) stockmove.product = product[0] stockmove.quantity = Decimal(row['quantity']) stockmove.uom = getUOM(productUOMList, row['stock.move_uom']) stockmove.from_location = getLocation(locationlist, 'SUP') stockmove.to_location = getLocation( locationlist, row['stock.location_from']) stockmove.planned_date = planned_date stockmove.effective_date = effective_date stockmove.unit_price = Decimal( row['stock.move_unit_price']) if row['stock.move_cost_price'] == 'default': stockmove.cost_price = product[0].cost_price else: stockmove.cost_price = Decimal( row['stock.move_cost_price']) stockmove.save() moves.append(stockmove) finally: f.close()
def date_value(value): return date.strptime(value, "%Y-%m-%d")
def load_internal_shipment(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for internal shipment') readertest = csv.DictReader(f) for row in readertest: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name'], row['stock.location_from'], row['stock.location_to'], row['stock.move_effective_date'], row['stock.move_planned_date'], row['stock.move_unit_price'], row['stock.move_cost_price']) f.seek(0) print('Start import') StockShipmentInternal = Model.get('stock.shipment.internal') stockshipmentinternal = StockShipmentInternal() stockshipmentinternal.reference = filename LocationFrom = Model.get('stock.location') locationfrom = LocationFrom.find([('code', '=', row['stock.location_from'])]) stockshipmentinternal.from_location = locationfrom[0] LocationTo = Model.get('stock.location') locationto = LocationTo.find([('code', '=', row['stock.location_to'])]) stockshipmentinternal.to_location = locationto[0] stockshipmentinternal.effective_date = date.today() stockshipmentinternal.planned_date = date.today() stockshipmentinternal.save() reader = csv.DictReader(f) moves = [] if stockshipmentinternal.id > 0: for row in reader: print(row['code'], row['name'], row['description'], row['quantity'], row['stock.location_from'], row['stock.location_to']) StockMove = Model.get('stock.move') stockmove = StockMove() stockmove.shipment = stockshipmentinternal Product = Model.get('product.product') product = Product.find([('code', '=', row['code'])]) stockmove.product = product[0] stockmove.quantity = int(row['quantity']) stockmove.from_location = locationfrom[0] stockmove.to_location = locationto[0] if row['stock.move_effective_date'] == 'today': effective_date = date.today() else: effective_date = date.strptime( row['stock.move_effective_date'], "%Y-%m-%dT") stockmove.effective_date = effective_date if row['stock.move_planned_date'] == 'today': planned_date = date.today() else: planned_date = date.strptime( row['stock.move_planned_date'], "%Y-%m-%dT") stockmove.planned_date = planned_date stockmove.unit_price = Decimal(row['stock.move_unit_price']) if row['stock.move_cost_price'] == 'default': stockmove.cost_price = product[0].cost_price else: stockmove.cost_price = Decimal( row['stock.move_cost_price']) stockmove.save() moves.append(stockmove) finally: f.close()
def to_date(s: Date) -> date: return date.strptime(s, "%Y-%m-%d")
def valid_date(s): try: return date.strptime(s, "%Y-%m-%d") except ValueError: msg = "Not a valid date: '{0}'.".format(s) raise argparse.ArgumentTypeError(msg)
# Counts the number of times each day of the week occurs in the log file days = elements[1] # If date is not logged in dictionary, adds date to dictionary if days in dates: continue else: dates[days] = 1 print("This file will take a while to parse, however will provide fantastic information for you!") # Takes the keys from the Dates Dictionary and converts them to date objects dates_list = list(dates.keys()) for i in dates_list: date_object = date.strptime(i, "%d/%b/%Y") day_of_week = date_object.isoweekday() # Increases counter for days of week if day_of_week == 1: mon_count += 1 if day_of_week == 2: tue_count += 1 if day_of_week == 3: wed_count += 1 if day_of_week == 4: thu_count += 1 if day_of_week == 5: fri_count += 1 if day_of_week == 6: sat_count += 1 if day_of_week == 7:
def date(self): date_str, _ = self.key.id().split(self._DATE_ID_SEPARATOR) return date.strptime(self._DATE_FMT_STR)