-
Notifications
You must be signed in to change notification settings - Fork 857
Expand file tree
/
Copy pathinternals.py
More file actions
40 lines (28 loc) · 1.27 KB
/
internals.py
File metadata and controls
40 lines (28 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from datetime import datetime
from typing import Type, TypeVar, Union
def _from_iso_format_to_datetime(iso_datetime_str: str) -> datetime:
if "+" not in iso_datetime_str:
iso_datetime_str += "+00:00"
return datetime.fromisoformat(iso_datetime_str)
def _from_iso_format_to_unix_timestamp(iso_datetime_str: str) -> float:
return _from_iso_format_to_datetime(iso_datetime_str).timestamp()
TimestampType = TypeVar("TimestampType", float, int)
def _timestamp_to_type(ts: Union[TimestampType, datetime, str], target_type: Type[TimestampType]) -> TimestampType:
result: TimestampType
if isinstance(ts, target_type):
# unnecessary type casting makes pytype happy
result = target_type(ts)
# although a type of the timestamp is just checked,
# pytype doesn't consider the following line valid:
# result = ts
# see https://github.com/google/pytype/issues/1012
elif isinstance(ts, datetime):
result = target_type(ts.timestamp())
elif isinstance(ts, str):
try:
result = target_type(ts)
except ValueError:
result = target_type(_from_iso_format_to_unix_timestamp(ts))
else:
raise ValueError(f"Unsupported data format for timestamp {ts}")
return result