|
1 | 1 | from datetime import datetime, timedelta, timezone, tzinfo
|
2 | 2 |
|
| 3 | +import os |
| 4 | +import pickle |
3 | 5 | import regex as re
|
| 6 | +from pathlib import Path |
4 | 7 |
|
5 | 8 | from .timezones import timezone_info_list
|
6 | 9 |
|
@@ -85,7 +88,46 @@ def get_local_tz_offset():
|
85 | 88 |
|
86 | 89 |
|
87 | 90 | _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 | 91 | local_tz_offset = get_local_tz_offset()
|
| 92 | + |
| 93 | +DEFAULT_CACHE_PATH = ".dateparser_tz_cache.pkl" |
| 94 | + |
| 95 | +_tz_offsets = None |
| 96 | +_search_regex = None |
| 97 | +_search_regex_ignorecase = None |
| 98 | + |
| 99 | + |
| 100 | +def _load_offsets(cache = False): |
| 101 | + from dateparser import __version__ |
| 102 | + |
| 103 | + global _tz_offsets, _search_regex, _search_regex_ignorecase |
| 104 | + |
| 105 | + if cache: |
| 106 | + path = Path(os.environ.get("DATEPARSER_TZ_CACHE_PATH", DEFAULT_CACHE_PATH)) |
| 107 | + path.parents[0].mkdir(parents=True, exist_ok=True) |
| 108 | + |
| 109 | + try: |
| 110 | + with open(path, mode="rb") as file: |
| 111 | + version, _tz_offsets, _search_regex, _search_regex_ignorecase = pickle.load(file) |
| 112 | + |
| 113 | + if version == __version__: |
| 114 | + return |
| 115 | + except FileNotFoundError: |
| 116 | + pass |
| 117 | + except (ValueError, TypeError) as ex: |
| 118 | + from .utils import get_logger |
| 119 | + get_logger().error("Error loading tz cache: %s", ex) |
| 120 | + |
| 121 | + _tz_offsets = list(build_tz_offsets(_search_regex_parts)) |
| 122 | + _search_regex = re.compile("|".join(_search_regex_parts)) |
| 123 | + _search_regex_ignorecase = re.compile("|".join(_search_regex_parts), re.IGNORECASE) |
| 124 | + |
| 125 | + if cache: |
| 126 | + with open(path, mode="wb") as file: |
| 127 | + pickle.dump( |
| 128 | + (__version__, _tz_offsets, _search_regex, _search_regex_ignorecase), |
| 129 | + file, |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | +_load_offsets("DATEPARSER_TZ_CACHE" in os.environ) |
0 commit comments