Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/build/lib/airflow/serialization/serializers/datetime.py: 42%

36 statements  

« 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 

19 

20from datetime import date, datetime, timedelta 

21from typing import TYPE_CHECKING 

22 

23from pendulum import DateTime 

24from pendulum.tz import timezone 

25 

26from airflow.utils.module_loading import qualname 

27from airflow.utils.timezone import convert_to_utc, is_naive 

28 

29if TYPE_CHECKING: 

30 from airflow.serialization.serde import U 

31 

32__version__ = 1 

33 

34serializers = [date, datetime, timedelta, DateTime] 

35deserializers = serializers 

36 

37TIMESTAMP = "timestamp" 

38TIMEZONE = "tz" 

39 

40 

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) 

46 

47 tz = o.tzname() 

48 

49 return {TIMESTAMP: o.timestamp(), TIMEZONE: tz}, qn, __version__, True 

50 

51 if isinstance(o, date): 

52 return o.isoformat(), qualname(o), __version__, True 

53 

54 if isinstance(o, timedelta): 

55 return o.total_seconds(), qualname(o), __version__, True 

56 

57 return "", "", 0, False 

58 

59 

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])) 

63 

64 if classname == qualname(DateTime) and isinstance(data, dict): 

65 return DateTime.fromtimestamp(float(data[TIMESTAMP]), tz=timezone(data[TIMEZONE])) 

66 

67 if classname == qualname(timedelta) and isinstance(data, (str, float)): 

68 return timedelta(seconds=float(data)) 

69 

70 if classname == qualname(date) and isinstance(data, str): 

71 return date.fromisoformat(data) 

72 

73 raise TypeError(f"unknown date/time format {classname}")