繁花如伊
为了它的价值,我将 Pandas 数据帧保存到 Postgres 数据库,并且我想保留时区索引。我使用以下代码:class db_JsonEncodedDataFrameWithTimezone(db.TypeDecorator): """Enables JSON storage by encoding and decoding on the fly.""" impl = db.Text def process_bind_param(self, value, dialect): if value is not None and isinstance(value, pd.DataFrame): timezone = value.index.tz.zone df_json = value.to_json(orient="index") data = {'timezone': timezone, 'df': df_json, 'index_name': value.index.name} value = json.dumps(data) return value def process_result_value(self, value, dialect): if value is not None: data = json.loads(value) df = pd.read_json(data['df'], orient="index") df.index = df.index.tz_localize('UTC') df.index = df.index.tz_convert(data['timezone']) df.index.name = data['index_name'] value = df return value def compare_values(self, x, y): from pandas.util.testing import assert_frame_equal try: assert_frame_equal(x, y, check_names=True, check_like=True) return True except (AssertionError, ValueError, TypeError): return False