def get_local_time(time): from_zone = tz.gettz('UTC') to_zone = tz.gettz('CST') utc = datetime.strptime(get_normal_time(time), '%Y-%m-%d %H:%M:%S') utc = utc.replace(tzinfo=from_zone) local = utc.astimezone(to_zone) return datetime.strftime(local, "%Y-%m-%d %H:%M:%S")
def timestamp_date(arg): if arg == '1531188713': print( datetime.fromtimestamp(int(arg)).astimezone( tz.gettz('America/Chicago'))) return datetime.fromtimestamp(int(arg)).astimezone( tz.gettz('America/Chicago')).strftime('%b %d %y, %H:%M')
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = "EDC093" protocol_name = "INTE" protocol_number = "093" protocol_title = "" study_open_datetime = datetime(2019, 7, 31, 0, 0, 0, tzinfo=gettz("UTC")) study_close_datetime = datetime(2022, 12, 31, 23, 59, 59, tzinfo=gettz("UTC"))
def test_observation_time(mocker): start_time = datetime( year=2019, month=1, day=1, hour=0, minute=0, second=0, tzinfo=tz.gettz("Africa/Johannesburg"), ) exposure_time = 100 with mocker.patch.object( rss_obs, "observation_time", return_value=types.ObservationTime( end_time=start_time + timedelta(seconds=exposure_time), exposure_time=exposure_time * u.second, plane_id=1, resolution=exposure_time * u.second, start_time=start_time, ), ): observation_time = rss_obs.observation_time(1) assert observation_time.end_time == datetime( year=2019, month=1, day=1, hour=0, minute=1, second=40, tzinfo=tz.gettz("Africa/Johannesburg"), ) assert observation_time.exposure_time == Quantity(value=100, unit=u.second)
def get_room_date(clubhouse_page): room_date = clubhouse_page.find('span', class_="font-light").text rooms_date_information = clubhouse_page.find_all("span", class_="font-semibold") room_day = rooms_date_information[0].text room_hour = rooms_date_information[1].text correct_date = room_date + " " + room_day + " " + room_hour timezone_info = {"PST": tz.gettz('America/Los_Angeles')} convert_to_polish_timezone = tz.gettz("Europe/Warsaw") current_datetime = parse(correct_date, tzinfos=timezone_info) current_datetime = current_datetime.astimezone(convert_to_polish_timezone) return current_datetime
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = 'BHP066' protocol_number = '066' protocol_name = 'BCPP' protocol_title = 'Botswana Combination Prevention Project' subject_types = [ SubjectType('subject', 'Research Subject', Cap(model_name='bcpp_subject.subjectconsent', max_subjects=99999)), SubjectType('subject', 'Anonymous Research Subject', Cap(model_name='bcpp_subject.anonymousconsent', max_subjects=9999)), ] study_open_datetime = datetime( 2013, 10, 18, 0, 0, 0, tzinfo=gettz('UTC')) study_close_datetime = datetime( 2018, 12, 1, 0, 0, 0, tzinfo=gettz('UTC'))
def get_files_from_emission_bucket(filename): """ :param filename, example='test.zip' :return latest file version """ res = get_s3_emission_bucket_version() files_list = [] # loop to get the latest version of the file for i in res['Versions']: if i['Key'] == filename: files_list.append({ "Key": i['Key'], "LastModified": i['LastModified'], "Size": i['Size'] / 1024 }) else: print({"File not found"}) # Get the latest file based on datetime latest_file = max(files_list, key=lambda x: x['LastModified']) # Converting to IST Timezone timezone_ist = tz.gettz('Asia/Kolkata') latest_file['LastModified'] = latest_file['LastModified'].astimezone( timezone_ist) return latest_file
def create_project_months(self): project_dates = self.get_project_month_list() jst = tz.gettz('Asia/Tokyo') now = datetime.now(jst) for project_date in project_dates: calculator = Calculator(project_date, self.client_company.billing_site, self.client_company.bank_holiday_flag) project_month = ProjectMonth( project_month=project_date, billing_tax=self.client_company.billing_tax, deposit_date=calculator.get_deposit_date(), created_at=now, created_user=session['user']['user_name'], updated_at=now, updated_user=session['user']['user_name']) if self.billing_timing == BillingTiming.billing_by_month: money = self.get_estimated_total_amount_by_month() project_month.billing_estimated_money = money project_month.billing_confirmation_money = money else: if project_date == max(project_dates): project_month.billing_estimated_money = self.estimated_total_amount project_month.billing_confirmation_money = self.estimated_total_amount self.project_months.append(project_month) return self
def total_games_leader_board(won=True, points=None, global_stats=False): query = db.session.query( Player.id, Player.name, func.sum(func.coalesce(case([ (or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id), case([((Game.team1_score >= 150) if won else (Game.team1_score < 150), 1)])), (or_(Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), case([((Game.team2_score >= 150) if won else (Game.team2_score < 150), 1)])) ]), 0)).label('count'), ). \ select_from(Game). \ join(Player, or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id, Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), isouter=True) if global_stats: query = query.filter(Game.finished_at.isnot(None), (Game.points == points) if points else True) else: today = datetime.now() - timedelta(hours=8) beginning_of_year = datetime(today.year, 1, 1, 8, 0).astimezone(tz.gettz('UTC')) query = query.filter(Game.finished_at.isnot(None), Game.started_at.__gt__(beginning_of_year), (Game.points == points) if points else True) return query.group_by(Player.id). \ having(db.text('count > 0')). \ order_by(db.text('count DESC'))
def should_send_pca_alert(course_term, course_status): if get_current_semester() != course_term: return False add_drop_period = get_or_create_add_drop_period(course_term) return (get_bool("SEND_FROM_WEBHOOK", False) and (course_status == "O" or course_status == "C") and (add_drop_period.end is None or datetime.utcnow().replace( tzinfo=gettz(TIME_ZONE)) < add_drop_period.end))
def gettz(self) -> datetime.tzinfo: """ Get device timezone from context attributes https://smarthub-wbench.wesp.telekom.net/pages/smarthub_cloud/skill-spi/public/#attribute-types :return: """ timezone = self._get_attribute('timezone', 'UTC') return tz.gettz(timezone) or tz.tzutc()
def pca_registration_open(): """ Returns True iff PCA should be accepting new registrations. """ current_adp = get_or_create_add_drop_period( semester=get_current_semester()) return get_bool("REGISTRATION_OPEN", True) and ( current_adp.end is None or datetime.utcnow().replace(tzinfo=gettz(TIME_ZONE)) < current_adp.end)
def fetch_data(r): resp = r.get(LIVE_PRODUCTION_API_URL) data = resp.json() timestamp = arrow.get(data["lastmodified"], "HH:mm:ss A DD-MM-YYYY", tzinfo=tz.gettz('Asia/Baghdad')) return data["d"], timestamp.datetime
def __init__(self, obj: Dict[str, Any]) -> None: # noqa: D102 super().__init__(obj) self.__status = Status(obj) self.__data = {} # type: Dict[str, Any] for name in obj.keys(): self.__data[name] = obj.get(name, None) if self.__data["last_date"] is not None: self.__data["last_date"] = arrow_get( self.__data["last_date"], "DD.MM.YYYY HH:mm:ss", tzinfo=tz.gettz("Europe/Moscow")).datetime if self.__data["send_date"] is not None: self.__data["send_date"] = arrow_get( self.__data["send_date"], "DD.MM.YYYY HH:mm:ss", tzinfo=tz.gettz("Europe/Moscow")).datetime for name in ["send_timestamp", "last_timestamp"]: del self.__data[name]
def main(): URL = 'http://api.sunrise-sunset.org/json?lat=35.9391938&lng=-78.7880005,&formatted=0' r = requests.get(URL) r.raise_for_status() times = r.json() for k in times['results'].keys(): if isinstance(times['results'][k], str): ts = dt.datetime.strptime(times['results'][k], '%Y-%m-%dT%H:%M:%S%z') ts = ts.replace(tzinfo=tz.gettz('UTC')) ts = ts.astimezone(tz.gettz('America/New_York')) else: ts = '2020-06-08T09:58:06+00:00' ts = ' ' print(times['results'][k], ts, k) s = sun(lat=35.9391938, long=-78.7880005) print(s.sunrise(), s.solarnoon(), s.sunset())
def versus_leader_board(global_stats=False): players = aliased(Player) other_players = aliased(Player) query = db.session.query( players.id, players.name, other_players.id, other_players.name, func.sum(func.coalesce(case([ (and_(or_(Game.team1_player1_id == players.id, Game.team1_player2_id == players.id), not_(or_(Game.team1_player1_id == other_players.id, Game.team1_player2_id == other_players.id))), case([(Game.team1_score >= 150, Game.points)])), (and_(or_(Game.team2_player1_id == players.id, Game.team2_player2_id == players.id), not_(or_(Game.team2_player1_id == other_players.id, Game.team2_player2_id == other_players.id))), case([(Game.team2_score >= 150, Game.points)])) ]), 0)).label('wins_score'), func.sum(func.coalesce(case([ (and_(or_(Game.team1_player1_id == players.id, Game.team1_player2_id == players.id), not_(or_(Game.team1_player1_id == other_players.id, Game.team1_player2_id == other_players.id))), case([(Game.team1_score < 150, Game.points)])), (and_(or_(Game.team2_player1_id == players.id, Game.team2_player2_id == players.id), not_(or_(Game.team2_player1_id == other_players.id, Game.team2_player2_id == other_players.id))), case([(Game.team2_score < 150, Game.points)])) ]), 0)).label('loses_score'), func.sum(func.coalesce(case([ (and_(or_(Game.team1_player1_id == players.id, Game.team1_player2_id == players.id), not_(or_(Game.team1_player1_id == other_players.id, Game.team1_player2_id == other_players.id))), case([(Game.team1_score < 150, -1)], else_=1) * Game.points), (and_(or_(Game.team2_player1_id == players.id, Game.team2_player2_id == players.id), not_(or_(Game.team2_player1_id == other_players.id, Game.team2_player2_id == other_players.id))), case([(Game.team2_score < 150, -1)], else_=1) * Game.points) ]), 0)).label('balance'), ). \ select_from(Game). \ join(players, or_(Game.team1_player1_id == players.id, Game.team1_player2_id == players.id, Game.team2_player1_id == players.id, Game.team2_player2_id == players.id)). \ join(other_players, or_(Game.team1_player1_id == other_players.id, Game.team1_player2_id == other_players.id, Game.team2_player1_id == other_players.id, Game.team2_player2_id == other_players.id)) if global_stats: query = query.filter(Game.finished_at.isnot(None)) else: today = datetime.now() - timedelta(hours=8) beginning_of_year = datetime(today.year, 1, 1, 8, 0).astimezone(tz.gettz('UTC')) query = query.filter(Game.finished_at.isnot(None), Game.started_at.__gt__(beginning_of_year)) return query.group_by(players.id, other_players.id). \ having(or_(db.text('wins_score > 0'), db.text('loses_score > 0'))). \ order_by(db.text(request.args.get('versus_leader_board_order_by', 'balance DESC, wins_score DESC')))
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = "BHP092" protocol_name = "Ambition" protocol_number = "092" protocol_title = "" study_open_datetime = datetime(2016, 12, 31, 0, 0, 0, tzinfo=gettz("UTC")) study_close_datetime = datetime(2022, 12, 31, 23, 59, 59, tzinfo=gettz("UTC"))
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = "BHP092" protocol_number = "092" protocol_name = "Ambition" protocol_title = "" year = datetime.now().year study_open_datetime = datetime(year, 1, 1, 0, 0, 0, tzinfo=gettz("UTC")) study_close_datetime = datetime(year + 5, 12, 31, 23, 59, 59, tzinfo=gettz("UTC"))
def now(cls, tz_str='Asia/Shanghai'): """ 获取当前时间 默认 时区 上海 :param tz_str: :return: """ from datetime import datetime from dateutil.tz import tz now = datetime.now(tz=tz.gettz(tz_str)) now = now.replace(tzinfo=None) return now
def save(self, model): jst = tz.gettz('Asia/Tokyo') now = datetime.now(jst) if model.id is None: model.created_at = now model.created_user = session['user']['user_name'] model.updated_at = now model.updated_user = session['user']['user_name'] db.session.add(model) db.session.commit() current_app.logger.debug('save:' + str(model))
def validate(self): mode = self.policy.data['mode'] if 'tz' in mode: error = PolicyValidationError( "policy:%s gcp-periodic invalid tz:%s" % (self.policy.name, mode['tz'])) # We can't catch all errors statically, our local tz retrieval # then the form gcp is using, ie. not all the same aliases are # defined. tzinfo = tz.gettz(mode['tz']) if tzinfo is None: raise error
def validate(self): mode = self.policy.data['mode'] if 'tz' in mode: error = PolicyValidationError( "policy:%s gcp-periodic invalid tz:%s" % ( self.policy.name, mode['tz'])) # We can't catch all errors statically, our local tz retrieval # then the form gcp is using, ie. not all the same aliases are # defined. tzinfo = tz.gettz(mode['tz']) if tzinfo is None: raise error
def leader_board(today=False, active=True, min_games_count=0, global_stats=False): query = db.session.query( Player.id, Player.name, (func.sum(func.coalesce(case([ (or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id), case([(Game.team1_score >= 150, Game.points)])), (or_(Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), case([(Game.team2_score >= 150, Game.points)])) ]), 0)) + (0 if today else Player.manual_wins)).label('wins_score'), (func.sum(func.coalesce(case([ (or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id), case([(Game.team1_score < 150, Game.points)])), (or_(Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), case([(Game.team2_score < 150, Game.points)])) ]), 0)) + (0 if today else Player.manual_loses)).label('loses_score'), (func.sum(func.coalesce(case([ (or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id), case([(Game.team1_score < 150, -1)], else_=1) * Game.points), (or_(Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), case([(Game.team2_score < 150, -1)], else_=1) * Game.points) ]), 0)) + (0 if today else (Player.manual_wins - Player.manual_loses))).label('balance'), func.sum(func.coalesce(case([ (or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id, Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), 1)], else_=0), 0)).label('games_count') ). \ select_from(Player). \ join(Game, or_(Game.team1_player1_id == Player.id, Game.team1_player2_id == Player.id, Game.team2_player1_id == Player.id, Game.team2_player2_id == Player.id), isouter=True) if today: today = datetime.now() - timedelta(hours=8) beginning_of_today = datetime(today.year, today.month, today.day, 8, 0).astimezone(tz.gettz('UTC')) query = query.filter(Game.finished_at.isnot(None), Game.started_at.__gt__(beginning_of_today)) else: if global_stats: query = query.filter(Game.finished_at.isnot(None)). \ having(db.text(f'games_count {">=" if active else "<"} {str(min_games_count)}')) else: today = datetime.now() - timedelta(hours=8) beginning_of_year = datetime(today.year, 1, 1, 8, 0).astimezone(tz.gettz('UTC')) query = query.filter(Game.finished_at.isnot(None), Game.started_at.__gt__(beginning_of_year)). \ having(db.text(f'games_count {">=" if active else "<"} {str(min_games_count)}')) return query. \ group_by(Player.id). \ order_by(db.text(request.args.get('leader_board_order_by', 'balance DESC, wins_score DESC')))
def create_post(faker, users_ids, replies): post = Post( title=faker.text(60), user_id=random.choice(users_ids), content=faker.text(random.randint(100, 1000)), created_at=faker.date_time_between( start_date="-10d", end_date="now", tzinfo=tz.gettz('UTC')), draft=random.choice([True, False]), ) post.save() if replies: add_random_replies(faker, post.id, users_ids)
def save(self, user): jst = tz.gettz('Asia/Tokyo') now = datetime.now(jst) if user.id is None: user.created_at = now user.created_user = session['user']['user_name'] user.password = bcrypt.generate_password_hash(user.shain_number) user.updated_at = now user.updated_user = session['user']['user_name'] db.session.add(user) db.session.commit() current_app.logger.debug('save:' + str(user))
def create_billing_at_last(self): project_dates = self.project.get_project_month_list() jst = tz.gettz('Asia/Tokyo') now = datetime.now(jst) project_billing = ProjectBilling( billing_month=max(project_dates), billing_content=self.work_name, billing_confirmation_money=self.billing_money, created_at=now, created_user=session['user']['user_name'], updated_at=now, updated_user=session['user']['user_name']) self.project_billings.append(project_billing) return self
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = 'BHP099' protocol_number = '099' protocol_name = 'TestApp' protocol_title = '' study_open_datetime = datetime(2007, 12, 31, 0, 0, 0, tzinfo=gettz('UTC')) study_close_datetime = datetime(2019, 12, 31, 0, 0, 0, tzinfo=gettz('UTC')) @property def site_name(self): return 'Gaborone'
def change_email_request(): form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data.lower() token = current_user.generate_email_change_token(new_email) send_email(new_email, 'Confirm your email address', 'auth/email/change_email', user=current_user, token=token, current_time=datetime.now(tz.gettz('CST')).strftime("%B %d, %Y %H:%M CST")) flash('An email with instructions to confirm your new email address has been sent to ' + new_email + '.', 'alert-info') return redirect(url_for('main.index')) else: flash('Invalid email or password.', 'alert_danger') return render_template('auth/change_email.html', form=form)
class EdcProtocolAppConfig(BaseEdcProtocolAppConfig): protocol = "BHP099" protocol_number = "099" protocol_name = "TestApp" protocol_title = "" study_open_datetime = datetime(2007, 12, 31, 0, 0, 0, tzinfo=gettz("UTC")) study_close_datetime = datetime(2019, 12, 31, 0, 0, 0, tzinfo=gettz("UTC")) @property def site_name(self): return "Gaborone"
def tow_factor_reset_request(): if not current_user.is_anonymous: flash("Since you have access to your 2FA, you don't need to reset it. You can change it directly.", 'alert-info') return redirect(url_for('auth.change_two_factor')) form = TwoFactorResetForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data.lower()).first() if user is not None and user.verify_password(form.password.data): token = user.generate_two_factor_reset_token() send_email(user.email, 'Reset Your 2FA', 'auth/email/reset_two_factor', user=user, token=token, current_time=datetime.now(tz.gettz('CST')).strftime("%B %d, %Y %H:%M CST")) flash('An email with instructions to reset your 2FA has been sent to you.', 'alert-primary') flash('Invalid email or password.', 'alert-danger') return render_template('auth/reset_tow_factor.html', form=form)
def password_reset_request(): if not current_user.is_anonymous: flash("Since you know your current password, you don't need to reset it. You can change it directly.", 'alert-info') return redirect(url_for('auth.change_password')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data.lower()).first() if user: token = user.generate_reset_token() send_email(user.email, 'Reset Your Password', 'auth/email/reset_password', user=user, token=token, current_time=datetime.now(tz.gettz('CST')).strftime("%B %d, %Y %H:%M CST")) flash('An email with instructions to reset your password has been sent to you.', 'alert-primary') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)