|
1 | | -import sys |
2 | 1 | from datetime import datetime |
3 | 2 |
|
| 3 | +_zoneinfo_available = True |
4 | 4 | try: |
5 | 5 | from zoneinfo import ZoneInfo, available_timezones |
6 | | - |
7 | | - USE_ZONEINFO = True |
8 | 6 | except ImportError: |
9 | 7 | try: |
10 | 8 | import pytz |
11 | 9 |
|
12 | | - USE_ZONEINFO = False |
13 | | - # Definisci available_timezones fittizio per compatibilità |
14 | | - if not hasattr(sys.modules[__name__], "available_timezones"): |
| 10 | + _zoneinfo_available = False |
15 | 11 |
|
16 | | - def available_timezones(): |
17 | | - return [] |
| 12 | + def available_timezones(): |
| 13 | + return [] |
18 | 14 |
|
19 | 15 | except ImportError: |
20 | | - print("Error: pytz not installed. Run: pip install pytz") |
21 | | - sys.exit(1) |
| 16 | + _zoneinfo_available = False |
| 17 | + ZoneInfo = None |
| 18 | + pytz = None |
| 19 | + |
| 20 | + def available_timezones(): |
| 21 | + return [] |
22 | 22 |
|
23 | 23 |
|
24 | 24 | def convert_timezone( |
25 | 25 | dt_str: str, from_tz: str, to_tz: str, date_format: str = "%Y-%m-%d %H:%M" |
26 | 26 | ) -> str: |
27 | 27 | try: |
28 | | - if USE_ZONEINFO: |
29 | | - # Verifica che i fusi siano validi |
| 28 | + if not _zoneinfo_available: |
| 29 | + if pytz is None: |
| 30 | + raise ValueError("pytz not installed") |
| 31 | + from_pytz = pytz.timezone(from_tz) |
| 32 | + to_pytz = pytz.timezone(to_tz) |
| 33 | + dt_naive = datetime.strptime(dt_str, date_format) |
| 34 | + dt_from = from_pytz.localize(dt_naive) |
| 35 | + dt_to = dt_from.astimezone(to_pytz) |
| 36 | + else: |
30 | 37 | if from_tz not in available_timezones(): |
31 | 38 | raise ValueError(f"Fuso orario non valido: {from_tz}") |
32 | 39 | if to_tz not in available_timezones(): |
33 | 40 | raise ValueError(f"Fuso orario non valido: {to_tz}") |
34 | 41 | dt_naive = datetime.strptime(dt_str, date_format) |
35 | 42 | dt_from = dt_naive.replace(tzinfo=ZoneInfo(from_tz)) |
36 | 43 | dt_to = dt_from.astimezone(ZoneInfo(to_tz)) |
37 | | - else: |
38 | | - from_pytz = pytz.timezone(from_tz) |
39 | | - to_pytz = pytz.timezone(to_tz) |
40 | | - dt_naive = datetime.strptime(dt_str, date_format) |
41 | | - dt_from = from_pytz.localize(dt_naive) |
42 | | - dt_to = dt_from.astimezone(to_pytz) |
43 | 44 | return dt_to.strftime(date_format) |
44 | 45 | except Exception as e: |
45 | 46 | raise ValueError(f"Errore nella conversione: {e}") |
0 commit comments