def get_all_missing(): for keg in keg_ids: if keg_ids[keg]['location'] != 'brewery' and keg_ids[keg]['location'] != None: print('Keg {} is out. Location: {}'.format(keg, keg_ids[keg]['location'])) days_since_keg = datetime.toordinal(datetime.today()) - datetime.toordinal(keg_ids[keg]['keg_date']) print('Kegged {} days ago.'.format(days_since_keg)) print()
def order_normal_datebound(avg_order_per_day, stdev, start_date, end_date, pick_date_deviation): from datetime import datetime from random import normalvariate start_date = datetime.toordinal(start_date) end_date = datetime.toordinal(end_date) order_list = [] order_number = 0 for day in range(end_date - start_date): today_order_count = max( [int(normalvariate(avg_order_per_day, stdev)), 0]) for order in range(today_order_count): order = [] order_number = order_number + 1 order_date = datetime.fromordinal(day + start_date) order_pick_date = datetime.fromordinal(day + start_date + pick_date_deviation) order_customer = "Costumer {}".format(order_number) order.append(order_number) order.append(order_date.strftime('%Y/%m/%d')) order.append(order_pick_date.strftime('%Y/%m/%d %X')) order.append(order_customer) order.append(order_number) order_list.append(order) return order_list
def convertDateToHour(date=None): """ converts the date passed as parameter into hours """ if date is None: date = DateTime() # The Zope DateTime object passed as parameter must be transformed into # python datetime object, to use toordinal method in conversion to hours creation_date_dict = {} for key in ('year', 'month', 'day'): method = getattr(date, key) creation_date_dict[key] = method() # formating the date from Zope DateTime format to python datetime format # and this provides the use of toordinal method. formatted_creation_date = datetime(creation_date_dict['year'], creation_date_dict['month'], creation_date_dict['day']) # reference date which is the first day of creation date year reference_date = datetime(creation_date_dict['year'], 01, 1) # calculate the ordinal date of the creation date and the reference date ordinal_date = datetime.toordinal(formatted_creation_date) ordinal_reference_date = datetime.toordinal(reference_date) hour_ = (ordinal_date - ordinal_reference_date ) * number_of_hours_in_day + number_of_hours_in_day + date.hour() return int(hour_)
def create_lookup(EMdat_data, start, end, disaster_subtype='Tropical cyclone'): """create_lookup: prepare a lookup table of EMdat events to which hazards can be assigned Parameters: EMdat_data: pd.dataframe with EMdat data start: start date of events to be assigned 'yyyy-mm-dd' end: end date of events to be assigned 'yyyy-mm-dd' disaster_subtype: EMdat disaster subtype Returns: pd.dataframe lookup """ data = EMdat_data[EMdat_data['Disaster_subtype'] == disaster_subtype] lookup = pd.DataFrame(columns = ['hit_country', 'Date_start_EM', \ 'Date_start_EM_ordinal', 'Disaster_name', \ 'EM_ID', 'ibtracsID', 'allocation_level', \ 'possible_track', 'possible_track_all']) lookup.hit_country = data.ISO lookup.Date_start_EM = data.Date_start_clean lookup.Disaster_name = data.Disaster_name lookup.EM_ID = data.Disaster_No lookup = lookup.reset_index(drop=True) # create ordinals for i in range(0, len(data.Date_start_clean.values)): lookup.Date_start_EM_ordinal[i] = datetime.toordinal(datetime.strptime(lookup.Date_start_EM.values[i], '%Y-%m-%d')) # ordinals to numeric lookup.Date_start_EM_ordinal = pd.to_numeric(lookup.Date_start_EM_ordinal) # select time EM_start = datetime.toordinal(datetime.strptime(start, '%Y-%m-%d')) EM_end = datetime.toordinal(datetime.strptime(end, '%Y-%m-%d')) lookup = lookup[lookup.Date_start_EM_ordinal.values > EM_start] lookup = lookup[lookup.Date_start_EM_ordinal.values < EM_end] return lookup
def monthlyavg(years, months, datas): #monthly averages for each year list_years=np.linspace(years[1],years[-1],1+years[-1]-years[1]) list_months=np.linspace(1,12,12) nmin=1 #min number of observations per month mdatas, myears, mmonths, mods, mdatasok, myearsok, mmonthsok, modsok = [], [], [], [], [], [], [], [] for year in list_years: for month in list_months: cdatas=[] for i in range(1, len(datas)): if not np.isnan(datas[i]) and years[i]==year and months[i]==month: cdatas.append(datas[i]) if len(cdatas)>0: mdata=sum(cdatas)/float(len(cdatas)) mdatas.append(mdata) myears.append(year) mmonths.append(month) mods.append(datetime.toordinal(datetime(int(year),int(month),1))) if len(cdatas)>nmin: mdatasok.append(mdata) myearsok.append(year) mmonthsok.append(month) modsok.append(datetime.toordinal(datetime(int(year),int(month),1))) return(mdatas, myears, mmonths, mods, mdatasok, myearsok, mmonthsok, modsok)
def __sale(price, create_date): """применение скидки если товару больше 30 дней""" sale = 20 # % скидка if abs( datetime.toordinal(datetime.utcnow()) - datetime.toordinal(create_date)) > 30: return price - (price * sale / 100) return price
def max_date(date1, date2): try: if datetime.toordinal(datetime.strptime( date1, "%d/%m/%Y")) - datetime.toordinal( datetime.strptime(date2, "%d/%m/%Y")) <= 0: return date2 else: return date1 except Exception as e: return str()
def time2num(tIn): tOut = [] try: for t1 in tIn: tOut.append( datetime.toordinal(t1) + t1.hour / 24. + t1.minute / (24. * 60.) + t1.second / (24. * 3600.)) except TypeError: t1 = tIn tOut = datetime.toordinal(t1) + t1.hour / 24. + t1.minute / ( 24. * 60.) + t1.second / (24. * 3600.) return tOut
def difference(date1, date2=''): '''calculates difference between two dates input date1,date2(optional),if only one date is given,calculates difference from real today output difference in terms of number of days ''' if not date2: return datetime.toordinal(datetime.today()) - datetime.toordinal( datetime.strptime(date1, "%d/%m/%Y")) else: return datetime.toordinal(datetime.strptime( date1, "%d/%m/%Y")) - datetime.toordinal( datetime.strptime(date2, "%d/%m/%Y"))
def interaction_curve_func(msgs, username=None, start_date=None, end_date=None, show_graph=False): ''' Use Linear Regression to predict whether there has been an increase or decrease in the number of messages ''' cur_date = '' cur_freq = 0 dates = [] str_dates = [] freqs = [] for msg in msgs: date = msg['date'] user = msg['username'] if (not username or user == username) and (not start_date or (date >= start_date and date <= end_date)): if cur_date == '': cur_date = date elif date != cur_date: dates.append(datetime.toordinal(cur_date)) str_dates.append(str(cur_date)) freqs.append(cur_freq) cur_date = date cur_freq = 0 cur_freq += 1 dates.append(datetime.toordinal(cur_date)) str_dates.append(str(cur_date)) freqs.append(cur_freq) # Reshaping to get a (n X 1)D array x = np.array(dates).reshape(-1, 1) y = np.array(freqs).reshape(-1, 1) linear_regressor = LinearRegression() linear_regressor.fit(x, y) y_pred = linear_regressor.predict(x) slope_sign_pred = (y_pred[1][0] - y_pred[0][0]) / abs(y_pred[1][0] - y_pred[0][0]) print('{} interactions in this chat have {}!'.format( 'Your' if username else 'The', 'decreased' if slope_sign_pred < 0 else 'increased' )) # For Graph if show_graph and CAN_SHOW_GRAPH: print('Showing graph....') plt.plot(x, y, 'o', color='black') # The point plot plt.plot(x, y_pred, color='red') # The line plot plt.xticks(dates, str_dates) plt.locator_params(axis='x', nbins=4) plt.show()
def get_today_accept_count(user): url = 'https://codeforces.com/api/user.status?handle='+user response = requests.get(url) parsed_response = response.json() if parsed_response['status'] == 'FAILED': print('[FAILED]: ', contestant, ': Not Found') return -1 today = datetime.toordinal(datetime.now()) sub_count = 0 for submission in parsed_response['result']: sub_day = datetime.fromtimestamp(submission['creationTimeSeconds']) sub_day = datetime.toordinal(sub_day) if sub_day == today and submission['verdict'] == 'OK': sub_count += 1 return sub_count
def csvfile_to_dataframe(input_file, date_format='%Y%j'): """ Return sorted filenames of images from input text file Args: input_file (str): text file of dates and files date_format (str): format of dates in file Returns: pd.DataFrame: pd.DataFrame of dates, sensor IDs, and filenames """ df = pd.read_csv(input_file) # Guess and convert date field date_col = [i for i, n in enumerate(df.columns) if 'date' in n.lower()] if not date_col: raise KeyError('Could not find date column in input file') if len(date_col) > 1: logger.warning('Multiple date columns found in input CSV file. ' 'Using %s' % df.columns[date_col[0]]) date_col = df.columns[date_col[0]] df[date_col] = pd.to_datetime( df[date_col], format=date_format).map(lambda x: dt.toordinal(x)) return df
def generate_metadata(self): """Generate metadata from list of metadata files.""" if len(self.files) > 0: this_netcdf = self.files[0].file_location ds, df_summ = self.files[0].process_netcdf(netcdf=this_netcdf) self.license = ds.attrs['license'] self.title = ds.attrs['title'] self.creator = ds.attrs['creator_name'] self.creator_email = ds.attrs['creator_email'] self.institution = ds.attrs['institution'] self.aknowledgements = ds.attrs['acknowledgement'] self.feature_type = ds.attrs['featureType'] self.summary = ds.attrs['summary'] self.conventions = ds.attrs['Conventions'] self.naming_authority = ds.attrs['naming_authority'] if self.date is None: from datetime import datetime self.date = datetime.fromordinal( datetime.toordinal(datetime( year=self.year, month=1, day=1) ) + self.doy - 1 ) self.month = self.date.month self.day = self.date.day self.parse_files() self.save() slack.chat.post_message( '#mpalatower', self.slack(), username='******', icon_emoji=':package:') return self else: return "No files found for %d, day of year %d" \ % (self.year, self.doy)
class ClientFriends(Client): today = datetime.toordinal(datetime.now()) age_friends = {} def __init__(self, user_id): self.user_id = user_id self.payload = {'v': '5.57', 'fields': 'bdate', 'order': 'random', 'user_id': self.user_id} def get_friends(self): resp = self._get_data('friends.get', self.payload) for i in range(len(resp['response']['items'])): if 'bdate' in resp['response']['items'][i]: if len(resp['response']['items'][i]['bdate']) >= 8: bdate = datetime.strptime(resp['response']['items'][i]['bdate'], '%d.%m.%Y') bdate = datetime.toordinal(bdate) age = int((self.today - bdate)//365.25) if self.age_friends.get(age) is None: self.age_friends[age] = 0 else: self.age_friends[age] += 1 return self.age_friends def print_friends(self): ages = self.get_friends() for i in range(max(ages.keys())+1): if ages.get(i): print(i, ages.get(i))
def generate_metadata(self): """Generate metadata from list of metadata files.""" if len(self.files) > 0: this_netcdf = self.files[0].file_location ds, df_summ = self.files[0].process_netcdf(netcdf=this_netcdf) self.license = ds.attrs['license'] self.title = ds.attrs['title'] self.creator = ds.attrs['creator_name'] self.creator_email = ds.attrs['creator_email'] self.institution = ds.attrs['institution'] self.aknowledgements = ds.attrs['acknowledgement'] self.feature_type = ds.attrs['featureType'] self.summary = ds.attrs['summary'] self.conventions = ds.attrs['Conventions'] self.naming_authority = ds.attrs['naming_authority'] if self.date is None: from datetime import datetime self.date = datetime.fromordinal( datetime.toordinal(datetime(year=self.year, month=1, day=1)) + self.doy - 1) self.month = self.date.month self.day = self.date.day self.parse_files() self.save() slack.chat.post_message('#mpalatower', self.slack(), username='******', icon_emoji=':package:') return self else: return "No files found for %d, day of year %d" \ % (self.year, self.doy)
def reading(fil): #reading file import csv readCSV = csv.reader(open(path + fil), delimiter='\t') # initialization dates, years, months, datas, odays = [], [], [], [], [] i = 0 for row in readCSV: if i == 0: lts = eval(row[0])-1 if i == lts: year1 = eval(row[1]) if i >= lts: date = row[0] year = row[1] month = row[2] day = row[3] data = row[7] #conversion ordinal day oday=datetime.toordinal(datetime(int(year),int(month),int(day))) #put in lists dates.append(date) years.append(float(year)) months.append(float(month)) datas.append(float(data)) odays.append(oday) i = i+1 return(dates, years, months, datas, odays)
def get_date_dataframe(column): from datetime import datetime from dateutil.parser import parse date_column = column.map(parse) def season_dist(date, season): """ # season 0 spring 1 summer 2 fall 3 winter """ day = [datetime(2000, 3, 20), datetime(2000, 6, 21), datetime(2000, 9, 22), datetime(2000, 12, 21)][season] year = date.year return min(abs(date - day.replace(year=yr)).days for yr in range(year-1, year+2)) date_df = pd.DataFrame({ "SaleYear": [d.year for d in date_column], "SaleMonth": [d.month for d in date_column], "SaleDay": [d.day for d in date_column], "Ordinal": [datetime.toordinal(d) for d in date_column] }, index=date_column.index) seasons = ["Spring", "Summer", "Fall", "Winter"] for i in range(4): date_df[seasons[i]] = [season_dist(d, i) for d in date_column] return date_df
def plot(self): ''' Simple plot. Be sure to call this method *after* calling extract_discharge_at_latlon, otherwise there is no data to plot. This results in such a figure: .. figure:: _static/dynrout_rhine.png :width: 900px :align: center :height: 400px ''' t = self.data['time'] q = self.data['q'] mpl.rc('font',**{'family':'serif','sans-serif':['Palatino']}) time = [] # Convert to datetime objects for i in t: time.append(datetime.fromordinal(int(i)+datetime.toordinal(datetime(1900,1,1)))) fig,ax = mpl.pyplot.subplots(1) ax.plot(time,q,color='#551A8B',label='Discharge') ax.grid(True) mpl.pyplot.ylabel('Discharge [$m^3s^{-1}$]') mpl.pyplot.title('Rhine River at the border of The Netherlands and Germany') fig.autofmt_xdate() ax.fmt_xdata = mdates.DateFormatter('%y-%m-%d') mpl.pyplot.ion() mpl.pyplot.show()
def change_location(keg_id): new_location = input('New location for keg #{}: '.format(keg_id)) keg_ids[keg_id]['location'] = new_location now = datetime.now().replace(second=0, microsecond=0) keg_ids[keg_id]['last_change'] = 'changed location to {} at {}'.format(new_location, now) keg_ids[keg_id]['last_change_ord'] = datetime.toordinal(now) print('Location changed to {}.'.format(new_location)) print()
def load_users(self): three_days_before_date = datetime.toordinal(datetime.now()) - 3 three_days_before_date = datetime.fromordinal(three_days_before_date) raw_data = self.request("select user_id from LastMessageTime where date >= %s;", (three_days_before_date, )) for result in raw_data: user_id = int(result[0]) self.users[user_id] = self.load_data(user_id)
def get_regression_model(self): x = self.df_indo['date'].transform( lambda d: datetime.toordinal(d)).values y = self.df_indo.iloc[:, 3].values # Initial guess p0 = [max(y), np.median(x), 1, min(y)] # Use logistic regression (sigmoid function) self.sigmoid_coeff, _ = curve_fit(self.sigmoid, x, y, p0) return self.sigmoid_coeff
def _ordinal_converter(self, x): if np.isnan(x): return np.nan x = float(x) + datetime.toordinal(datetime(1899, 12, 31)) ord_date = date.fromordinal(int(np.floor(x))) return datetime(ord_date.year, ord_date.month, ord_date.day, int(np.floor((x % 1.0) * 24)), int(np.round((x % 1.0 * 24 % 1.0 * 60), decimals=0)))
def order_datebound(order_per_day,start_date,end_date,pick_date_deviation): from datetime import datetime start_date = datetime.toordinal(start_date) end_date = datetime.toordinal(end_date) order_list = [] order_number = 0 for day in range(end_date-start_date): for order in range(order_per_day): order = [] order_number =order_number +1 order_date = datetime.fromordinal(day+start_date) order_pick_date = datetime.fromordinal(day + start_date+pick_date_deviation) order_customer = "Costumer {}".format(order_number) order.append(order_number) order.append(order_date.strftime('%Y/%m/%d')) order.append(order_pick_date.strftime('%Y/%m/%d %X')) order.append(order_customer) order.append(order_number) order_list.append(order) return order_list
def get_regression_total_case_accuracy(self): if self.sigmoid_coeff is None: self.get_regression_model() # Predict data x_data = self.df_indo['date'].transform( lambda d: datetime.toordinal(d)).values y_data = self.df_indo['total_cases'].values y_pred = self.sigmoid(x_data, *self.sigmoid_coeff) print('RMSE (root mean squared error)', mean_squared_error(y_data, y_pred)) print('R^2 (coefficient of determination)', r2_score(y_data, y_pred))
def __call__(self, event): # Plot X/Y clicked x, y = event.x, event.y # Bands plotted on each axis plotted = (settings.plot['y_axis_1_band'], settings.plot['y_axis_2_band']) # Store output as a set images = set() for ax, _plotted in zip(event.canvas.axes, plotted): # If nothing plotted on this axis, continue if not np.any(_plotted): continue # Setup transform for going from data to plot coordinates trans = ax.transData # Check bands that are plotted on current axis on = np.where(_plotted)[0] on_series = settings.plot_series[on] on_band = settings.plot_band_indices[on] for i, j in zip(on_series, on_band): # Switch based on plot type if isinstance(event.canvas, plots.TSPlot): _X, _y = tsm.ts.get_data(i, j, mask=False) _x = _X['ordinal'] elif isinstance(event.canvas, plots.ResidualPlot): residuals = tsm.ts.get_residuals(i, j) if residuals is None: return _x = np.array([dt.toordinal(_d) for _d in np.concatenate(residuals[0])]) _y = np.concatenate(residuals[1]) elif isinstance(event.canvas, plots.DOYPlot): _X, _y = tsm.ts.get_data(i, j, mask=False) _x = _X['doy'] # Transform data into plot coordinates trans_coords = trans.transform(np.vstack((_x, _y)).T) _x, _y = trans_coords[:, 0], trans_coords[:, 1] delta_x = np.abs(_x - x) delta_y = np.abs(_y - y) delta = np.linalg.norm(np.vstack((delta_x, delta_y)), axis=0) clicked = np.where(delta < self.tolerance)[0] for _clicked in clicked: # Add index of series and index of image images.add((i, _clicked)) self.picked.emit(images)
def change_contents(keg_id): old_contents = keg_ids[keg_id]['contents'] new_contents = input('New contents for keg #{}: '.format(keg_id)) keg_ids[keg_id]['contents'] = new_contents now = datetime.now().replace(second=0, microsecond=0) keg_ids[keg_id]['last_change'] = 'changed contents to {} at {}'.format(new_contents, now) keg_ids[keg_id]['last_change_ord'] = datetime.toordinal(now) if old_contents == 'empty' and new_contents != 'empty': keg_ids[keg_id]['keg_date'] = datetime.today().replace(second=0, microsecond=0) print('Contents changed to: {}'.format(new_contents)) print()
def order_datebound(order_per_day, start_date, end_date, pick_date_deviation): from datetime import datetime start_date = datetime.toordinal(start_date) end_date = datetime.toordinal(end_date) order_list = [] order_number = 0 for day in range(end_date - start_date): for order in range(order_per_day): order = [] order_number = order_number + 1 order_date = datetime.fromordinal(day + start_date) order_pick_date = datetime.fromordinal(day + start_date + pick_date_deviation) order_customer = "Costumer {}".format(order_number) order.append(order_number) order.append(order_date.strftime('%Y/%m/%d')) order.append(order_pick_date.strftime('%Y/%m/%d %X')) order.append(order_customer) order.append(order_number) order_list.append(order) return order_list
def set_done_date(self, task_id): date = datetime.toordinal(datetime.today()) cursor = self.connection.cursor() cursor.execute( '''UPDATE tasks SET done_date = ? WHERE id = ?''', ( date, task_id, )) cursor.close() self.connection.commit()
def get_friends(self): resp = self._get_data('friends.get', self.payload) for i in range(len(resp['response']['items'])): if 'bdate' in resp['response']['items'][i]: if len(resp['response']['items'][i]['bdate']) >= 8: bdate = datetime.strptime(resp['response']['items'][i]['bdate'], '%d.%m.%Y') bdate = datetime.toordinal(bdate) age = int((self.today - bdate)//365.25) if self.age_friends.get(age) is None: self.age_friends[age] = 0 else: self.age_friends[age] += 1 return self.age_friends
def convertDateToHour(date=None): """ converts the date passed as parameter into hours """ if date is None: date = DateTime() # The Zope DateTime object passed as parameter must be transformed into # python datetime object, to use toordinal method in conversion to hours creation_date_dict = {} for key in ('year', 'month', 'day'): method = getattr(date, key) creation_date_dict[key] = method() # formating the date from Zope DateTime format to python datetime format # and this provides the use of toordinal method. formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day']) # reference date which is the first day of creation date year reference_date = datetime(creation_date_dict['year'], 01, 1) # calculate the ordinal date of the creation date and the reference date ordinal_date = datetime.toordinal(formatted_creation_date) ordinal_reference_date = datetime.toordinal(reference_date) hour = (ordinal_date - ordinal_reference_date) * number_of_hours_in_day + number_of_hours_in_day + date.hour() return int(hour)
def order_normal_datebound(avg_order_per_day,stdev,start_date,end_date,pick_date_deviation): from datetime import datetime from random import normalvariate start_date = datetime.toordinal(start_date) end_date = datetime.toordinal(end_date) order_list = [] order_number = 0 for day in range(end_date-start_date): today_order_count = max([int(normalvariate(avg_order_per_day,stdev)),0]) for order in range(today_order_count): order = [] order_number =order_number +1 order_date = datetime.fromordinal(day+start_date) order_pick_date = datetime.fromordinal(day + start_date+pick_date_deviation) order_customer = "Costumer {}".format(order_number) order.append(order_number) order.append(order_date.strftime('%Y/%m/%d')) order.append(order_pick_date.strftime('%Y/%m/%d %X')) order.append(order_customer) order.append(order_number) order_list.append(order) return order_list
def _ordinal_converter(self, x): if np.isnan(x): return np.nan x = float(x) + datetime.toordinal(datetime(1899, 12, 31)) ord_date = date.fromordinal(int(np.floor(x))) return datetime( ord_date.year, ord_date.month, ord_date.day, int(np.floor((x % 1.0) * 24)), int(np.round((x % 1.0 * 24 % 1.0 * 60), decimals=0)), )
def get_day_and_class_name_from_text(text): t = text.split() for i in range(len(t)): if t[i] in ['дз', 'домашнее', 'задание', 'домашка']: continue else: ind = i break else: return ['', ''] now = datetime.now() today = make_date(now) tomorrow = make_date(datetime.fromordinal(datetime.toordinal(now) + 1)) yesterday = make_date(datetime.fromordinal(datetime.toordinal(now) - 1)) w = now.weekday() mon = datetime.fromordinal(datetime.toordinal(now) - w) sun = datetime.fromordinal(datetime.toordinal(now) - w + 5) monday = make_date(mon) sunday = make_date(sun) week = monday + '-' + sunday try: class_name = t[ind] day = t[ind + 1] except Exception: return [today, t[ind]] class_name = class_name.upper() if day == 'сегодня': day = today elif day == 'завтра': day = tomorrow elif day == 'вчера': day = yesterday elif day == 'неделя': day = week return [day, class_name]
def get_time(year, daynumber): """ Converts the year and day of year to get a base time in seconds since 1970 for the GPS week. This is so the data can be compared with POSIX time. """ # subtract 1 because the first day of the year does not start with zero ordinal = datetime.toordinal(datetime(year, 1, 1)) + daynumber - 1 dow = datetime.fromordinal(ordinal).weekday() + 1 if dow == 7: # shift sunday to be start of week. dow = 0 # 1970-1-1 is julian day 719163 POSIXdays = ordinal - 719163 - dow basetime = POSIXdays * 24 * 3600 return basetime
def plot_expected_new_case(self, fig, ax, pred_d): x = self.df_indo['date'].transform( lambda d: datetime.toordinal(d)).values # Predict using the sigmoid curve if self.sigmoid_coeff is None: self.get_regression_model() # Next n day, to be predicted x_pred = np.append(x, [i for i in range(x[-1] + 1, x[-1] + pred_d + 1)]) # y value predicted total_case = self.sigmoid(x_pred, *self.sigmoid_coeff) new_case = [0] max_new_case = -1 max_new_case_idx = -1 for i in range(1, len(total_case)): if total_case[i] < 0 or total_case[i - 1] < 0: new_case.append(0) else: new_case_daily = total_case[i] - total_case[i - 1] new_case.append(new_case_daily) # Get max new case if new_case_daily > max_new_case: max_new_case = new_case_daily max_new_case_idx = i new_case = np.array(new_case) plt.plot(x_pred, new_case, color='red', linewidth=4) ax.set_ylim(bottom=0) # Aditional info print("New case:") print("Max new case in a day =", int(max_new_case)) print("Max new case date =", str(datetime.fromordinal(x_pred[max_new_case_idx])).split()[0]) under_1_new_case = False under_5_new_case = False under_10_new_case = False for case, date in zip(reversed(new_case), reversed(x_pred)): if case > 1 and not under_1_new_case: under_1_new_case = True print("New case under 1 date =", str(datetime.fromordinal(date + 1)).split()[0]) if case > 5 and not under_5_new_case: under_5_new_case = True print("New case under 5 date =", str(datetime.fromordinal(date + 1)).split()[0])
def in_range(self): #Possibly get rid of getdates() function -- just do request.get when necessary. datestrs = self.getdates() begin_date = datetime.strptime(datestrs[0], '%Y-%m-%d') end_date = datetime.strptime(datestrs[1], '%Y-%m-%d') #make function for this so that both begin_date/end_date & holiday_begin/holiday_end #can use it. if datetime.toordinal(begin_date) > datetime.toordinal(end_date): in_range = False error = 'Error: begin date should come before end date' elif datetime.toordinal(end_date) - datetime.toordinal(begin_date) > 100: in_range = False error = 'Error: begin date & end date too far apart' else: in_range = True error = '' #for extended holiday holiday_begin = self.request.get('holiday_begin') holiday_end = self.request.get('holiday_end') if (holiday_begin and holiday_end) and in_range == True: holiday_begin = datetime.strptime(holiday_begin, '%Y-%m-%d') holiday_end = datetime.strptime(holiday_end, '%Y-%m-%d') if datetime.toordinal(holiday_begin) > datetime.toordinal(holiday_end): in_range = False error = 'begin_date > end_date' elif datetime.toordinal(holiday_end) - datetime.toordinal(holiday_begin) > 100: in_range = False error = 'Error: Holiday length too long' else: in_range = True error = '' return in_range, error
def populate_calendar(self): db_files = set(self.getValues('file_name', tables.calendar_files)) disk_files = set(os.listdir(self.settings.paths['calendar'])) files = list( filter(lambda x: x.endswith('.json'), disk_files.difference(db_files))) for f in files: file_path = ''.join((self.settings.paths['calendar'] + f)) with open(file_path, 'r') as json_file: cal = json.load(json_file) if len(cal) > 0: out_data = dict() out_data['date'] = cal['date'] out_data['file_name'] = f out_data['pdate'] = datetime.toordinal( datetime.strptime(cal['date'], '%Y-%m-%d')) out_data['tracks'] = len(cal['tracks']) out_data['games'] = len(cal['games']) out_data['file_size'] = os.path.getsize(file_path) out_data['scraped'] = False self.write2db(out_data, tables.calendar_files)
def plot_expected_total_case(self, fig, ax, pred_d): x = self.df_indo['date'].transform( lambda d: datetime.toordinal(d)).values # Predict using the sigmoid curve if self.sigmoid_coeff is None: self.get_regression_model() # Next n day, to be predicted x_pred = np.append(x, [i for i in range(x[-1] + 1, x[-1] + pred_d + 1)]) total_case = self.sigmoid(x_pred, *self.sigmoid_coeff) # Plot data plt.plot(x_pred, total_case, color='red', linewidth=4) ax.set_ylim(bottom=0) # Additional info print('Total case:') print(f'Total kasus positif {pred_d} hari dari tanggal 5 Mei 2020 =', int(total_case[-1]), 'orang') y_data = self.df_indo['total_cases'].values print('RMSE (root mean squared error)', mean_squared_error(y_data, total_case[:len(y_data)])) print('R^2 (coefficient of determination)', r2_score(y_data, total_case[:len(y_data)])) # Return return fig, ax
def timeslation(timestr): # translates record timestamp string into a datetime format month = timestr[4:7] if month == "Jan": month = '01' elif month == "Feb": month = '02' elif month == "Mar": month = '03' elif month == "Apr": month = '04' elif month == "May": month = '05' elif month == "Jun": month = '06' elif month == "Jul": month = '07' elif month == "Aug": month = '08' elif month == "Sep": month = '09' elif month == "Oct": month = '10' elif month == "Nov": month = '11' elif month == "Dec": month = '12' else: return datetime.toordinal(1) date = timestr[8:10] time = timestr[11:19] year = timestr[20:24] return datetime.strptime(year + '-' + month + '-' + date + ' ' + time, '%Y-%m-%d %H:%M:%S')
from datetime import datetime now = datetime.now() now_d = datetime.toordinal(now) # Amount of days till 0000 answer = ['YES, you can stay, she came from night today - 3', 'NO, gotta go home, man. She works day tomorrow - 4', 'YES, you can stay, she works day today - 1', 'NO, gotta go home, man. She works night today - 2'] f_answer = ['YES, you can stay, she will come from night that day - 3', # Answers for queries in future 'NO, will have to go home, man. She will work day next day - 4', 'YES, you can stay, she works day that day - 1', 'NO, will have to go home, man. She will work night that day - 2'] week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] print(answer[now_d % 4]) # Print current schedule for p in range(30): x1 = int(input()) # Insert day or year if x1 > 1000: # Case where user wants to check another year x2 = int(input()) # Insert day x3 = int(input()) # Insert month try: # Checking for wrong date input now_d = datetime.toordinal(now.replace(x1,x3,x2)) except ValueError: print('Insert the right date') continue
def rangeofdates(self, begin, end): x = range(datetime.toordinal(begin), datetime.toordinal(end) + 1) return [self.makedate(i) for i in x]
pass else: print("Аккаунт " + account + " не подходит по количеству постов") logging.info("Аккаунт " + account + " не подходит по количеству постов") print("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time)) logging.info("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time)) write_in_file(BAD_ACC, account) continue # Конец проверки по количеству постов # Проверка на дату последнего поста if LAST_POST_SW: last_post_date = last_post_date_pt.findall(page) if last_post_date: last_post_date = time.gmtime(int(last_post_date[0])) last_post_date = datetime(year=last_post_date[0], month=last_post_date[1], day=last_post_date[2]) last_post_date = datetime.toordinal(last_post_date) now_date = datetime.toordinal(datetime.now()) if (now_date - last_post_date) <= LAST_POST_DAYS: pass else: print("Аккаунт " + account + " не проходит по дате последнего поста") logging.info("Аккаунт " + account + " не проходит по дате последнего поста") print("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time)) logging.info("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time)) write_in_file(BAD_ACC, account) continue else: print("Аккаунт " + account + " не имеет постов") logging.info("Аккаунт " + account + " не имеет постов") print("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time)) logging.info("Завершено за: {0:.5f} секунд\n".format(timeit.default_timer() - start_time))
from selenium import webdriver from selenium.webdriver.common.keys import Keys from datetime import datetime weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] year = datetime.now().year month = datetime.now().month day = datetime.now().day+1 now = datetime.now() my_password = '******' if datetime.weekday(now) == 4: # Task given on Friday try: # If it's not the end of a month datetime.toordinal(now.replace(year,month,day+1)) date = str(day+2) + '.' + str(month) + '.' + str(year) except ValueError: try: # if there's last day after Friday datetime.toordinal(now.replace(year,month,day)) date = '1' + '.' + str(month+1) + '.' + str(year) except ValueError: # Friday is the last day date = '2' + '.' + str(month+1) + '.' + str(year) subject = 'GMCL. Tasks for Monday (' + date + ')' else: # Task given on any other day try: # If it's not the end of a month datetime.toordinal(now.replace(year,month,day)) date = str(day) + '.' + str(month) + '.' + str(year) except ValueError: # If it's the end of a month date = '1' + '.' + str(month+1) + '.' + str(year) subject = 'GMCL. Tasks for ' + weekday[datetime.weekday(now)+1] + ' (' + date + ')'
if season == 'summer': summer=np.array(sdatasok) if season == 'autumn': autumn=np.array(sdatasok) if season == 'winter': winter=np.array(sdatasok) i, j= 0, 0 # yearly averages (if 4 seasons available) yods, ydatas, ydatasok, mdatasok = [], [], [], [] for y in years: j = j + 1 # x axis for plotting the dates yods.append(datetime.toordinal(datetime(int(y),6,15))) #sum of nan -> 0 if not np.nansum(spring[i,:])==0 and not np.nansum(summer[i,:])==0 and not np.nansum(autumn[i,:])==0 and not np.nansum(winter[i,:])==0: ydata=np.nanmean([spring[i],summer[i],autumn[i],winter[i]], axis=0) ydatas.append(ydata) ydatasok.append(ydata) #check months for the year anf flag as ok #for j in range(0,len(mdatas)): # if int(myears[j])==y: # mdatasok.append(mdatas[j]) else: ydata=np.nanmean([spring[i],summer[i],autumn[i],winter[i]], axis=0) ydatas.append(ydata) ydatasok.append(nanmat) #for j in range(0,len(mdatas)):
# else: # tau, pval, spyr = float('NaN'), float('NaN'), float('NaN') # # #listing of statistics # taus.append(tau), pvals.append(pval), spyrs.append(spyr) #plotting import matplotlib.pyplot as plt import matplotlib.dates as mdates #vertical axis import math if param=='od550aer': ylab=r"${AOD_{550}}$" ymin, ymax = 0, math.ceil(max(meas_mdatas)*10)/10 xmin, xmax = datetime.toordinal(datetime(2000,1,1)), datetime.toordinal(datetime(2011,12,31)) from pylab import * figure(num=None, figsize=(10, 3), dpi=80, facecolor='w', edgecolor='k') ax=gca(); #plot fig = plt.plot_date(meas_mods,meas_mdatas,color="#1f77b4", markersize=4.5, markeredgewidth=0.0, alpha=0.3) if len(meas_mdatasok)>0: plt.plot_date(meas_modsok,meas_mdatasok,color="#1f77b4", markersize=4.5, markeredgewidth=0.0, alpha=1.0) plt.plot_date(meas_mods,meas_mdatas,color="#1f77b4", linestyle='-', linewidth=2.3, markersize=0.0, markeredgewidth=0.0, alpha=0.2) fig = plt.plot_date(mod_mods,mod_mdatas,color="#e93737", markersize=4.5, markeredgewidth=0.0, alpha=0.3) if len(mod_mdatasok)>0: plt.plot_date(mod_modsok,mod_mdatasok,color="#e93737", markersize=4.5, markeredgewidth=0.0, alpha=1.0) plt.plot_date(mod_mods,mod_mdatas,color="#e93737", linestyle='-', linewidth=2.3, markersize=0.0, markeredgewidth=0.0, alpha=0.2)
def _init_images(self, images, date_index=[9, 16], date_format='%Y%j'): n = len(images) if n == 0: raise Exception('Cannot initialize a Series of 0 images') else: self.n = n logger.debug('Trying to initialize a Series of %i images' % self.n) # Extract images information _images = np.empty(self.n, dtype=self.images.dtype) for i, img in enumerate(images): _images[i]['filename'] = os.path.basename(img) _images[i]['path'] = img _images[i]['id'] = os.path.basename(os.path.dirname(img)) try: date = _images[i]['id'][date_index[0]:date_index[1]] date = dt.strptime(date, date_format) except: try: date = _images[i]['filename'][date_index[0]:date_index[1]] date = dt.strptime(date, date_format) except: raise Exception( 'Could not parse date from ID or filename ' '(date index=%s:%s, format=%s)\n%s\n%s' % (date_index[0], date_index[1], date_format, _images[i]['id'], _images[i]['filename']) ) _images[i]['date'] = date _images[i]['ordinal'] = dt.toordinal(_images[i]['date']) _images[i]['doy'] = int(_images[i]['date'].strftime('%j')) sort_idx = np.argsort(_images['ordinal']) _images = _images[sort_idx] self.images = _images.copy() # Extract attributes self.gt = None self.crs = None ds = None for fname in images: try: ds = gdal.Open(fname, gdal.GA_ReadOnly) except: pass else: break if ds is None: raise Exception('Could not initialize attributes for %s series: ' 'could not open any images in Series with GDAL' % self.description) self.band_names = [] for i_b in range(ds.RasterCount): name = ds.GetRasterBand(i_b + 1).GetDescription() if not name: name = 'Band %s' % str(i_b + 1) self.band_names.append(name) self.width = ds.RasterXSize self.height = ds.RasterYSize self.count = ds.RasterCount self.dtype = gdal_array.GDALTypeCodeToNumericTypeCode( ds.GetRasterBand(1).DataType) self.gt = ds.GetGeoTransform() self.crs = ds.GetProjection()
def date_str_toordinal(date_str): x_date = datetime.strptime(date_str, '%Y-%m-%d') return datetime.toordinal(x_date)
def year_to_date(settlement,year): return (datetime.toordinal(settlement)+ year*(365))
# - - - - - - - - - - - - - - - - - - - - - - - # just to plot on the map: tau, pval, spyr = float('NaN'), float('NaN'), float('NaN') #listing of statistics taus.append(tau), pvals.append(pval), spyrs.append(spyr) #plotting import matplotlib.pyplot as plt import matplotlib.dates as mdates #vertical axis import math from datetime import datetime xmin, xmax = datetime.toordinal(datetime(yrmin,1,1)), datetime.toordinal(datetime(yrmax,12,31)) if param=='e355': xlab=r"${\sigma_ {ext,355}\ (km^{-1})}$" ylab=r"${Altitude_{AGL}\ (km)}$" xax_fmt="%3.2f" xspace=0.1 xmin, xmax = 0, 0.8 ymin, ymax = 0, 10 if param=='e532': xlab=r"${\sigma_ {ext,532}\ (km^{-1})}$" ylab=r"${Altitude_{AGL}\ (km)}$" xax_fmt="%3.2f" xspace=0.1 xmin, xmax = 0, 0.4 ymin, ymax = 0, 10 if param=='e1064':
def year_frac (settlement, t): return ((datetime.toordinal(t) - datetime.toordinal(settlement))/365)
dates, years, months, datas, odays = [], [], [], [], [] i = 0 for row in readCSV: if i == 0: lts = eval(row[0])-1 if i == lts: year1 = eval(row[1]) if i >= lts: date = row[0] year = row[1] month = row[2] day = row[3] data = row[7] if avgtime=='daily': #conversion ordinal day oday=datetime.toordinal(datetime(int(year),int(month),int(day))) else: #conversion ordinal day oday=datetime.toordinal(datetime(int(year),int(month),int(1))) #put in lists if in period if float(year)>=yrmin and float(year)<=yrmax: dates.append(date) years.append(float(year)) months.append(float(month)) datas.append(float(data)) odays.append(oday) i = i+1 # - - - - Model- - - - - -
#!/usr/local/bin/python # coding: utf-8 from datetime import datetime, date, time today_date = date.today() print("сегодня") print(today_date) #не сообразил как сделать на одной строке( print() deadline_date = date(2016, 12, 31) #вроде можно получать дату вводом пользователя, но сходу не сработало print("осталось") days_left = datetime.toordinal(deadline_date) - datetime.toordinal(today_date) print(days_left) current_weight = input() goal_weight = 90.0 weight_left = current_weight - goal_weight weight_loose_per_day = weight_left / days_left round_weight = round(weight_loose_per_day,2) print(round_weight)