def process_data(self, value: datetime) -> None: if value is not None: if not value.tzinfo: if self.use_naive: value = get_timezone().localize(value) else: value = utc_dt(value) if not self.use_naive: value = value.astimezone(get_timezone()) super().process_data(value)
def process_data(self, value): if value is not None: if not value.tzinfo: if self.use_naive: value = get_timezone().localize(value) else: value = utc_dt(value) if not self.use_naive: value = value.astimezone(get_timezone()) super().process_data(value)
def process_formdata(self, valuelist): if valuelist: date_str = " ".join(valuelist) locale = get_locale() date_fmt = locale.date_formats["short"] date_fmt = babel2datetime(date_fmt) date_fmt = date_fmt.replace("%B", "%m").replace( "%b", "%m" ) # force numerical months time_fmt = locale.time_formats["short"] time_fmt = babel2datetime(time_fmt) datetime_fmt = f"{date_fmt} | {time_fmt}" try: self.data = datetime.datetime.strptime(date_str, datetime_fmt) if not self.use_naive: tz = get_timezone() if self.data.tzinfo: self.data = self.data.astimezone(tz) else: self.data = tz.localize(self.data) # convert to UTC self.data = utc_dt(self.data) except ValueError: self.data = None raise ValueError(self.gettext("Not a valid datetime value"))
def format_datetime(dt, *, convert_tz=False, show_tz=False): """ Format a `datetime` object into a localized form. :param datetime dt: The datetime object to format. :param bool convert_tz: Whether to convert the value to Babel's timezone. :param bool show_tz: Whether to print the timezone's name in the result. This can only be set to `True` when `convert_tz` is also `True`. :return str: The localized version of the datetime object. """ if show_tz and not convert_tz: # Only implemented showing the timezone when converting. raise ValueError parts = [ dates.format_datetime(dt, format='short', tzinfo=get_timezone() if convert_tz else None, locale=get_locale()), ] if show_tz: parts.append(f"({get_timezone().tzname(dt)})") return ' '.join(parts)
def process_formdata(self, valuelist: List[str]) -> None: if valuelist: date_str = " ".join(valuelist) locale = get_locale() date_fmt = locale.date_formats["short"] date_fmt = babel2datetime(date_fmt) date_fmt = date_fmt.replace("%B", "%m").replace( "%b", "%m") # force numerical months time_fmt = locale.time_formats["short"] time_fmt = babel2datetime(time_fmt) datetime_fmt = f"{date_fmt} | {time_fmt}" try: self.data = datetime.strptime(date_str, datetime_fmt) if not self.use_naive: tz = get_timezone() if self.data.tzinfo: self.data = self.data.astimezone(tz) else: self.data = tz.localize(self.data) # convert to UTC self.data = utc_dt(self.data) except ValueError: self.data = None raise ValueError(self.gettext("Not a valid datetime value"))
def process_formdata(self, valuelist): if valuelist: date_str = ' '.join(valuelist) locale = get_locale() date_fmt = locale.date_formats['short'] date_fmt = babel2datetime(date_fmt) date_fmt = date_fmt \ .replace('%B', '%m') \ .replace('%b', '%m') # force numerical months time_fmt = locale.time_formats['short'] time_fmt = babel2datetime(time_fmt) datetime_fmt = u'{} | {}'.format(date_fmt, time_fmt) try: self.data = datetime.datetime.strptime(date_str, datetime_fmt) if not self.use_naive: tz = get_timezone() if self.data.tzinfo: self.data = self.data.astimezone(tz) else: self.data = tz.localize(self.data) # convert to UTC self.data = utc_dt(self.data) except ValueError: self.data = None raise ValueError(self.gettext('Not a valid datetime value'))
def process_formdata(self, valuelist): if valuelist: date_str = ' '.join(valuelist) locale = get_locale() date_fmt = locale.date_formats['short'] date_fmt = babel2datetime(date_fmt) date_fmt = date_fmt.replace('%B', '%m')\ .replace('%b', '%m') # force numerical months time_fmt = locale.time_formats['short'] time_fmt = babel2datetime(time_fmt) datetime_fmt = u'{} | {}'.format(date_fmt, time_fmt) try: self.data = datetime.datetime.strptime(date_str, datetime_fmt) if not self.use_naive: tz = get_timezone() if self.data.tzinfo: self.data = self.data.astimezone(tz) else: self.data = tz.localize(self.data) # convert to UTC self.data = utc_dt(self.data) except ValueError: self.data = None raise ValueError(self.gettext('Not a valid datetime value'))
def count_last_week_dayli_requests(): """ 获取上周的每日流量 """ from flask_babel import get_timezone from app.extensions.logger.models import Log from app.utils import local project = { "$project": { "cdate": { "$dateToString": { "format": "%Y-%m-%d", "date": "$created", "timezone": str(get_timezone()), } }, "day": { "$dayOfYear": { "timezone": str(get_timezone()), "date": "$created" } }, } } group = { "$group": { "_id": "$day", "date": { "$first": "$cdate" }, "cnt": { "$sum": 1 } } } sort = {"$sort": {"_id": 1}} a_week_ago = local.localdate().shift(weeks=-1) cursor = Log.objects(created__gte=a_week_ago, module__nin=["static", "admin", "unknown" ]).aggregate(project, group, sort) data = [i for i in cursor] labels = [i["date"] for i in data] cnts = [i["cnt"] for i in data] return {"labels": labels, "cnts": cnts}
def count_last_week_dayli_tasks(): """ 获取上周的每日任务数量 """ from flask_babel import get_timezone from app.extensions.celerybackend.models import Tasks from app.utils import local project = { "$project": { "cdate": { "$dateToString": { "format": "%Y-%m-%d", "date": "$time_start", "timezone": str(get_timezone()), } }, "day": { "$dayOfYear": { "timezone": str(get_timezone()), "date": "$time_start" } }, } } group = { "$group": { "_id": "$day", "date": { "$first": "$cdate" }, "cnt": { "$sum": 1 } } } sort = {"$sort": {"_id": 1}} a_week_ago = local.localdate().shift(weeks=-1) cursor = Tasks.objects(time_start__gte=a_week_ago).aggregate( project, group, sort) data = [i for i in cursor] labels = [i["date"] for i in data] cnts = [i["cnt"] for i in data] return {"labels": labels, "cnts": cnts}
def _serialize(self, value: Union[None, datetime.datetime], attr: Any, obj: Any, **kwargs: Any) -> Any: """序列化""" if value is None: return value timezone = str(get_timezone()) value = convert_timezone(instance(value), timezone) return super()._serialize(value, attr, obj, **kwargs)
def process_result_value(self, value, dialect): """ 从数据库中将时间转为arrow类型 """ from flask_babel import get_timezone if value: return arrow.get(value).to(str(get_timezone())) return value
def to_python(self, value): """ 从数据库中将时间转为arrow类型 """ from flask_babel import get_timezone if value: return arrow.get(value).to(str(get_timezone())) return value
def _deserialize(self, value: str, attr: Any, data: Any, **kwargs: Any) -> DateTime: """反序列化""" if not value: raise self.make_error("invalid", input=value, obj_type=self.OBJ_TYPE) timezone = get_timezone() dt = parse(value, tz=timezone) assert isinstance(dt, DateTime) return convert_timezone(dt, "utc")
def process_literal_param(self, value, dialect): """ 渲染内联的支持 """ from flask_babel import get_timezone val = self._coerce(value) print(val) if val.tzinfo == tz.UTC: val = val.replace(tzinfo=str(get_timezone())) utc_val = val.to("UTC") return utc_val.format("YYYY-MM-DD HH:mm:ss")
def process_bind_param(self, value, dialect): """ 处理数据到数据库 1. 替换UTC的时区为当当前时区,后转为当前时区 2. 转换非UTC时区的时间为当前时区 """ from flask_babel import get_timezone if value: val = self._coerce(value) if val.tzinfo == tz.UTC: val = val.replace(tzinfo=str(get_timezone())) utc_val = val.to("UTC") return utc_val.datetime if self.impl.timezone else utc_val.naive return value
def celery_worker_formatter(worker_info): """ e.g. {'celery@RedLotus': { '61421e6b-b933-412b-8f62-65425f312b69': [ 'active', { 'id': '61421e6b-b933-412b-8f62-65425f312b69', 'name': 'send_mail', 'args': '()', 'kwargs': '{}', 'type': 'send_mail', 'hostname': 'celery@RedLotus', 'time_start': 1565752238.579593, 'acknowledged': False, 'delivery_info': { 'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None }, 'worker_pid': 19696 } ] } } """ from flask_babel import get_timezone result = [] for _, task_info in worker_info.items(): for _, details in task_info.items(): state, info_dict = details tmp = {} tmp["state"] = state tmp.update(info_dict) tmp["time_start"] = arrow.get(tmp["time_start"]).to( str(get_timezone())) _id = uuid.UUID(tmp.pop("id")) tmp["id"] = _id result.append(tmp) return result
def format_datetime(dt, *, convert_tz=False, show_tz=False): """ Format a `datetime` object into a localized form. :param datetime dt: The datetime object to format. :param bool convert_tz: Whether to convert the value to Babel's timezone. :param bool show_tz: Whether to print the timezone's name in the result. :return str: The localized version of the datetime object. """ parts = [ dates.format_datetime(dt, format='short', tzinfo=get_timezone() if convert_tz else None, locale=get_locale()), ] if show_tz: if convert_tz: parts.append(f"({dt.astimezone(get_timezone()).tzname()})") else: parts.append(f"({dt.tzname()})") return ' '.join(parts)
def localnow(): """返回本地时间""" time = arrow.now(str(get_timezone())) return time