1
+ import os
2
+ import pickle
3
+ import zlib
1
4
from datetime import datetime , timedelta , timezone , tzinfo
5
+ from pathlib import Path
2
6
3
7
import regex as re
4
8
@@ -54,6 +58,12 @@ def convert_to_local_tz(datetime_obj, datetime_tz_offset):
54
58
return datetime_obj - datetime_tz_offset + local_tz_offset
55
59
56
60
61
+ def get_local_tz_offset ():
62
+ offset = datetime .now () - datetime .now (tz = timezone .utc ).replace (tzinfo = None )
63
+ offset = timedelta (days = offset .days , seconds = round (offset .seconds , - 1 ))
64
+ return offset
65
+
66
+
57
67
def build_tz_offsets (search_regex_parts ):
58
68
def get_offset (tz_obj , regex , repl = "" , replw = "" ):
59
69
return (
@@ -78,14 +88,44 @@ def get_offset(tz_obj, regex, repl="", replw=""):
78
88
yield get_offset (tz_obj , regex , repl = replace , replw = replacewith )
79
89
80
90
81
- def get_local_tz_offset ():
82
- offset = datetime .now () - datetime .now (tz = timezone .utc ).replace (tzinfo = None )
83
- offset = timedelta (days = offset .days , seconds = round (offset .seconds , - 1 ))
84
- return offset
91
+ local_tz_offset = get_local_tz_offset ()
85
92
93
+ _tz_offsets = None
94
+ _search_regex = None
95
+ _search_regex_ignorecase = None
96
+
97
+
98
+ def _load_offsets (cache_path , current_hash ):
99
+ global _tz_offsets , _search_regex , _search_regex_ignorecase
100
+
101
+ try :
102
+ with open (cache_path , mode = "rb" ) as file :
103
+ (
104
+ serialized_hash ,
105
+ _tz_offsets ,
106
+ _search_regex ,
107
+ _search_regex_ignorecase ,
108
+ ) = pickle .load (file )
109
+ if current_hash == serialized_hash :
110
+ return
111
+ except (FileNotFoundError , ValueError , TypeError ):
112
+ pass
113
+
114
+ _search_regex_parts = []
115
+ _tz_offsets = list (build_tz_offsets (_search_regex_parts ))
116
+ _search_regex = re .compile ("|" .join (_search_regex_parts ))
117
+ _search_regex_ignorecase = re .compile ("|" .join (_search_regex_parts ), re .IGNORECASE )
118
+
119
+ with open (cache_path , mode = "wb" ) as file :
120
+ pickle .dump (
121
+ (current_hash , _tz_offsets , _search_regex , _search_regex_ignorecase ),
122
+ file ,
123
+ )
86
124
87
- _search_regex_parts = []
88
- _tz_offsets = list (build_tz_offsets (_search_regex_parts ))
89
- _search_regex = re .compile ("|" .join (_search_regex_parts ))
90
- _search_regex_ignorecase = re .compile ("|" .join (_search_regex_parts ), re .IGNORECASE )
91
- local_tz_offset = get_local_tz_offset ()
125
+
126
+ CACHE_PATH = Path (__file__ ).parent .joinpath ("data" , "dateparser_tz_cache.pkl" )
127
+
128
+ _load_offsets (
129
+ cache_path = CACHE_PATH ,
130
+ current_hash = zlib .crc32 (str (timezone_info_list ).encode ("utf-8" )),
131
+ )
0 commit comments