Debian Codegraph @

gallery_dl/dt.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2025 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Date/Time utilities"""
10
11 import sys
12 import time
13 from datetime import datetime, date, timedelta, timezone # noqa F401
14
15
16 class NullDatetime(datetime):
17
18 def __bool__(self):
19 return False
20
21 def __str__(self):
22 return "[Invalid DateTime]"
23
24 def __format__(self, format_spec):
25 return "[Invalid DateTime]"
26
27
28 NONE = NullDatetime(1, 1, 1)
29 EPOCH = datetime(1970, 1, 1)
30 SECOND = timedelta(0, 1)
31
32
33 def normalize(dt):
34 # if (o := dt.utcoffset()) is not None:
35 # return dt.replace(tzinfo=None, microsecond=0) - o
36 if dt.tzinfo is not None:
37 return dt.astimezone(timezone.utc).replace(tzinfo=None, microsecond=0)
38 if dt.microsecond:
39 return dt.replace(microsecond=0)
40 return dt
41
42
43 def convert(value):
44 """Convert 'value' to a naive UTC datetime object"""
45 if not value:
46 return NONE
47 if isinstance(value, datetime):
48 return normalize(value)
49 if isinstance(value, str) and (dt := parse_iso(value)) is not NONE:
50 return dt
51 return parse_ts(value)
52
53
54 def parse(dt_string, format):
55 """Parse 'dt_string' according to 'format'"""
56 try:
57 return normalize(datetime.strptime(dt_string, format))
58 except Exception:
59 return NONE
60
61
62 if sys.hexversion < 0x30c0000:
63 # Python <= 3.11
64 def parse_iso(dt_string):
65 """Parse 'dt_string' as ISO 8601 value"""
66 try:
67 if dt_string[-1] == "Z":
68 # compat for Python < 3.11
69 dt_string = dt_string[:-1]
70 elif dt_string[-5] in "+-":
71 # compat for Python < 3.11
72 dt_string = f"{dt_string[:-2]}:{dt_string[-2:]}"
73 return normalize(datetime.fromisoformat(dt_string))
74 except Exception:
75 return NONE
76
77 from_ts = datetime.utcfromtimestamp
78 now = datetime.utcnow
79
80 else:
81 # Python >= 3.12
82 def parse_iso(dt_string):
83 """Parse 'dt_string' as ISO 8601 value"""
84 try:
85 return normalize(datetime.fromisoformat(dt_string))
86 except Exception:
87 return NONE
88
89 def from_ts(ts=None):
90 """Convert Unix timestamp to naive UTC datetime"""
91 Y, m, d, H, M, S, _, _, _ = time.gmtime(ts)
92 return datetime(Y, m, d, H, M, S)
93
94 now = from_ts
95
96
97 def parse_ts(ts, default=NONE):
98 """Create a datetime object from a Unix timestamp"""
99 try:
100 return from_ts(int(ts))
101 except Exception:
102 return default
103
104
105 def to_ts(dt):
106 """Convert naive UTC datetime to Unix timestamp"""
107 return (dt - EPOCH) / SECOND
108
109
110 def to_ts_string(dt):
111 """Convert naive UTC datetime to Unix timestamp string"""
112 try:
113 return str((dt - EPOCH) // SECOND)
114 except Exception:
115 return ""