Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/build/lib/airflow/serialization/serializers/datetime.py: 32%
38 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
20from typing import TYPE_CHECKING
22from airflow.utils.module_loading import qualname
23from airflow.utils.timezone import convert_to_utc, is_naive
25if TYPE_CHECKING:
26 import datetime
28 from airflow.serialization.serde import U
30__version__ = 1
32serializers = ["datetime.date", "datetime.datetime", "datetime.timedelta", "pendulum.datetime.DateTime"]
33deserializers = serializers
35TIMESTAMP = "timestamp"
36TIMEZONE = "tz"
39def serialize(o: object) -> tuple[U, str, int, bool]:
40 from datetime import date, datetime, timedelta
42 if isinstance(o, datetime):
43 qn = qualname(o)
44 if is_naive(o):
45 o = convert_to_utc(o)
47 tz = o.tzname()
49 return {TIMESTAMP: o.timestamp(), TIMEZONE: tz}, qn, __version__, True
51 if isinstance(o, date):
52 return o.isoformat(), qualname(o), __version__, True
54 if isinstance(o, timedelta):
55 return o.total_seconds(), qualname(o), __version__, True
57 return "", "", 0, False
60def deserialize(classname: str, version: int, data: dict | str) -> datetime.date | datetime.timedelta:
61 import datetime
63 from pendulum import DateTime
64 from pendulum.tz import timezone
66 if classname == qualname(datetime.datetime) and isinstance(data, dict):
67 return datetime.datetime.fromtimestamp(float(data[TIMESTAMP]), tz=timezone(data[TIMEZONE]))
69 if classname == qualname(DateTime) and isinstance(data, dict):
70 return DateTime.fromtimestamp(float(data[TIMESTAMP]), tz=timezone(data[TIMEZONE]))
72 if classname == qualname(datetime.timedelta) and isinstance(data, (str, float)):
73 return datetime.timedelta(seconds=float(data))
75 if classname == qualname(datetime.date) and isinstance(data, str):
76 return datetime.date.fromisoformat(data)
78 raise TypeError(f"unknown date/time format {classname}")