Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/airflow/serialization/serializers/datetime.py: 42%
36 statements
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +0000
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +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 datetime import date, datetime, timedelta
21from typing import TYPE_CHECKING
23from pendulum import DateTime
24from pendulum.tz import timezone
26from airflow.utils.module_loading import qualname
27from airflow.utils.timezone import convert_to_utc, is_naive
29if TYPE_CHECKING:
30 from airflow.serialization.serde import U
32__version__ = 1
34serializers = [date, datetime, timedelta, DateTime]
35deserializers = serializers
37TIMESTAMP = "timestamp"
38TIMEZONE = "tz"
41def serialize(o: object) -> tuple[U, str, int, bool]:
42 if isinstance(o, DateTime) or 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 | timedelta | date:
61 if classname == qualname(datetime) and isinstance(data, dict):
62 return datetime.fromtimestamp(float(data[TIMESTAMP]), tz=timezone(data[TIMEZONE]))
64 if classname == qualname(DateTime) and isinstance(data, dict):
65 return DateTime.fromtimestamp(float(data[TIMESTAMP]), tz=timezone(data[TIMEZONE]))
67 if classname == qualname(timedelta) and isinstance(data, (str, float)):
68 return timedelta(seconds=float(data))
70 if classname == qualname(date) and isinstance(data, str):
71 return date.fromisoformat(data)
73 raise TypeError(f"unknown date/time format {classname}")