0
# Timezone Support
1
2
Comprehensive timezone handling supporting UTC, fixed offsets, system local timezone, tzfile format, Windows registry timezones, iCalendar timezones, POSIX TZ strings, and advanced DST handling.
3
4
## Capabilities
5
6
### Core Timezone Classes
7
8
#### UTC Timezone
9
10
```python { .api }
11
class tzutc(tzinfo):
12
"""
13
UTC timezone implementation (singleton).
14
15
Standard tzinfo methods:
16
- utcoffset(dt) -> timedelta(0)
17
- dst(dt) -> timedelta(0)
18
- tzname(dt) -> "UTC"
19
- fromutc(dt) -> datetime
20
- is_ambiguous(dt) -> False
21
"""
22
23
# Predefined UTC instance
24
UTC = tzutc()
25
```
26
27
#### Fixed Offset Timezone
28
29
```python { .api }
30
class tzoffset(tzinfo):
31
def __init__(self, name, offset):
32
"""
33
Fixed UTC offset timezone.
34
35
Parameters:
36
- name (str): Timezone name/description
37
- offset (timedelta): UTC offset
38
"""
39
40
def utcoffset(self, dt):
41
"""Return the fixed offset."""
42
43
def dst(self, dt):
44
"""Return timedelta(0) - no DST."""
45
46
def tzname(self, dt):
47
"""Return the timezone name."""
48
```
49
50
**Usage Examples:**
51
52
```python
53
from dateutil.tz import tzutc, tzoffset, UTC
54
from datetime import datetime, timedelta
55
56
# UTC timezone
57
utc_dt = datetime.now(UTC)
58
utc_dt2 = datetime.now(tzutc()) # Same as UTC
59
60
# Fixed offset timezones
61
eastern_std = tzoffset("EST", timedelta(hours=-5))
62
india_std = tzoffset("IST", timedelta(hours=5, minutes=30))
63
64
dt_est = datetime(2023, 12, 25, 12, 0, tzinfo=eastern_std)
65
dt_ist = datetime(2023, 12, 25, 12, 0, tzinfo=india_std)
66
```
67
68
#### System Local Timezone
69
70
```python { .api }
71
class tzlocal(tzinfo):
72
"""
73
System local timezone with automatic DST handling.
74
75
Automatically detects system timezone and handles DST transitions.
76
"""
77
78
def utcoffset(self, dt):
79
"""Return system UTC offset for given datetime."""
80
81
def dst(self, dt):
82
"""Return DST offset for given datetime."""
83
84
def tzname(self, dt):
85
"""Return system timezone name."""
86
```
87
88
**Usage Examples:**
89
90
```python
91
from dateutil.tz import tzlocal
92
from datetime import datetime
93
94
local_tz = tzlocal()
95
local_time = datetime.now(local_tz)
96
print(f"Local time: {local_time}")
97
print(f"UTC offset: {local_tz.utcoffset(local_time)}")
98
print(f"DST offset: {local_tz.dst(local_time)}")
99
```
100
101
### File-Based Timezones
102
103
#### tzfile - Timezone from File
104
105
```python { .api }
106
class tzfile(tzinfo):
107
def __init__(self, fileobj, filename=None):
108
"""
109
Timezone from tzfile format (e.g., /usr/share/zoneinfo files).
110
111
Parameters:
112
- fileobj: File-like object with tzfile data
113
- filename (str, optional): Filename for reference
114
"""
115
116
def is_ambiguous(self, dt):
117
"""
118
Check if datetime is ambiguous during DST transition.
119
120
Returns:
121
bool: True if datetime occurs twice due to DST transition
122
"""
123
124
def fromutc(self, dt):
125
"""Convert UTC datetime to local timezone."""
126
```
127
128
**Usage Examples:**
129
130
```python
131
from dateutil.tz import tzfile
132
from datetime import datetime
133
134
# Load timezone from system file
135
with open('/usr/share/zoneinfo/America/New_York', 'rb') as f:
136
ny_tz = tzfile(f, 'America/New_York')
137
138
dt = datetime(2023, 12, 25, 12, 0, tzinfo=ny_tz)
139
print(f"Time in NY: {dt}")
140
print(f"Is ambiguous: {ny_tz.is_ambiguous(dt)}")
141
```
142
143
### Advanced Timezone Classes
144
145
#### tzrange - DST Rule-Based Timezone
146
147
```python { .api }
148
class tzrange(tzinfo):
149
def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None,
150
start=None, end=None):
151
"""
152
Timezone with explicit DST rules.
153
154
Parameters:
155
- stdabbr (str): Standard time abbreviation
156
- stdoffset (timedelta, optional): Standard time UTC offset
157
- dstabbr (str, optional): DST abbreviation
158
- dstoffset (timedelta, optional): DST UTC offset
159
- start (relativedelta, optional): DST start rule
160
- end (relativedelta, optional): DST end rule
161
"""
162
```
163
164
#### tzstr - POSIX TZ String Timezone
165
166
```python { .api }
167
class tzstr(tzrange):
168
def __init__(self, s, posix=True):
169
"""
170
Parse timezone from POSIX TZ environment string.
171
172
Parameters:
173
- s (str): TZ string (e.g., "EST5EDT,M3.2.0,M11.1.0")
174
- posix (bool): Use POSIX-style parsing
175
"""
176
```
177
178
**Usage Examples:**
179
180
```python
181
from dateutil.tz import tzstr
182
from datetime import datetime
183
184
# Parse POSIX TZ strings
185
eastern = tzstr("EST5EDT,M3.2.0,M11.1.0") # US Eastern
186
pacific = tzstr("PST8PDT,M3.2.0,M11.1.0") # US Pacific
187
188
dt = datetime(2023, 7, 15, 12, 0, tzinfo=eastern)
189
print(f"Eastern time: {dt}")
190
print(f"Pacific time: {dt.astimezone(pacific)}")
191
```
192
193
#### tzical - iCalendar Timezone
194
195
```python { .api }
196
class tzical:
197
def __init__(self, fileobj):
198
"""
199
Parse timezones from iCalendar (.ics) files.
200
201
Parameters:
202
- fileobj: File-like object with iCalendar data
203
"""
204
205
def get(self, name=None):
206
"""
207
Get timezone by name.
208
209
Parameters:
210
- name (str, optional): Timezone name, or None for default
211
212
Returns:
213
tzinfo: Timezone object
214
"""
215
216
def keys(self):
217
"""
218
Get list of available timezone names.
219
220
Returns:
221
list[str]: Available timezone names
222
"""
223
```
224
225
### Timezone Resolution Function
226
227
```python { .api }
228
def gettz(name=None):
229
"""
230
Get timezone by name with intelligent fallback.
231
232
Parameters:
233
- name (str, optional): Timezone name or None for local timezone
234
235
Returns:
236
tzinfo: Appropriate timezone object
237
238
Resolution order:
239
1. System zoneinfo if available (preferred)
240
2. dateutil bundled zoneinfo
241
3. Fixed offset if name looks like offset
242
4. Local timezone if name is None
243
5. None if unable to resolve
244
"""
245
```
246
247
**Usage Examples:**
248
249
```python
250
from dateutil.tz import gettz
251
from datetime import datetime
252
253
# Get various timezones
254
utc = gettz('UTC')
255
local = gettz() # System local timezone
256
ny = gettz('America/New_York')
257
tokyo = gettz('Asia/Tokyo')
258
london = gettz('Europe/London')
259
260
# Fixed offset styles
261
plus5 = gettz('+05:00')
262
minus8 = gettz('-0800')
263
264
# Create timezone-aware datetime
265
dt = datetime(2023, 12, 25, 12, 0, tzinfo=ny)
266
tokyo_time = dt.astimezone(tokyo)
267
```
268
269
### DST and Ambiguous Time Handling
270
271
```python { .api }
272
def enfold(dt, fold=1):
273
"""
274
Set fold attribute for ambiguous times during DST transitions.
275
276
Parameters:
277
- dt (datetime): Datetime to modify
278
- fold (int): Fold value (0 or 1)
279
280
Returns:
281
datetime: Datetime with fold attribute set
282
"""
283
284
def datetime_ambiguous(dt, tz=None):
285
"""
286
Check if datetime is ambiguous in timezone.
287
288
Parameters:
289
- dt (datetime): Datetime to check
290
- tz (tzinfo, optional): Timezone, uses dt.tzinfo if None
291
292
Returns:
293
bool: True if datetime is ambiguous
294
"""
295
296
def datetime_exists(dt, tz=None):
297
"""
298
Check if datetime exists in timezone.
299
300
Parameters:
301
- dt (datetime): Datetime to check
302
- tz (tzinfo, optional): Timezone, uses dt.tzinfo if None
303
304
Returns:
305
bool: True if datetime exists (not in DST gap)
306
"""
307
308
def resolve_imaginary(dt):
309
"""
310
Resolve non-existent times during DST transitions.
311
312
Parameters:
313
- dt (datetime): Potentially non-existent datetime
314
315
Returns:
316
datetime: Resolved datetime
317
"""
318
```
319
320
**Usage Examples:**
321
322
```python
323
from dateutil.tz import gettz, enfold, datetime_ambiguous, datetime_exists, resolve_imaginary
324
from datetime import datetime
325
326
eastern = gettz('America/New_York')
327
328
# DST transition handling
329
# Fall back: 2023-11-05 01:30 occurs twice
330
ambiguous_time = datetime(2023, 11, 5, 1, 30, tzinfo=eastern)
331
print(f"Is ambiguous: {datetime_ambiguous(ambiguous_time)}")
332
333
# Specify which occurrence using fold
334
first_occurrence = enfold(ambiguous_time, fold=0)
335
second_occurrence = enfold(ambiguous_time, fold=1)
336
337
# Spring forward: 2023-03-12 02:30 doesn't exist
338
nonexistent_time = datetime(2023, 3, 12, 2, 30, tzinfo=eastern)
339
print(f"Exists: {datetime_exists(nonexistent_time)}")
340
341
# Resolve the gap
342
resolved_time = resolve_imaginary(nonexistent_time)
343
print(f"Resolved to: {resolved_time}")
344
```
345
346
### Windows Timezone Support
347
348
```python { .api }
349
# Available only on Windows
350
class tzwin(tzinfo):
351
"""Windows registry-based timezone."""
352
353
class tzwinlocal(tzinfo):
354
"""Windows local timezone from registry."""
355
```
356
357
## Advanced Timezone Patterns
358
359
### Timezone Conversion Chains
360
361
```python
362
from dateutil.tz import gettz
363
from datetime import datetime
364
365
# Create timezone-aware datetime
366
utc = gettz('UTC')
367
dt_utc = datetime(2023, 12, 25, 17, 0, tzinfo=utc)
368
369
# Convert through multiple timezones
370
timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo', 'Australia/Sydney']
371
converted_times = {}
372
373
for tz_name in timezones:
374
tz = gettz(tz_name)
375
converted_times[tz_name] = dt_utc.astimezone(tz)
376
377
for tz_name, dt in converted_times.items():
378
print(f"{tz_name}: {dt}")
379
```
380
381
### Business Hours Across Timezones
382
383
```python
384
from dateutil.tz import gettz
385
from datetime import datetime, time
386
387
def is_business_hours(dt, timezone_name):
388
"""Check if datetime is during business hours in given timezone."""
389
tz = gettz(timezone_name)
390
local_dt = dt.astimezone(tz)
391
392
# Business hours: 9 AM - 5 PM, Monday-Friday
393
if local_dt.weekday() >= 5: # Weekend
394
return False
395
396
business_start = time(9, 0)
397
business_end = time(17, 0)
398
399
return business_start <= local_dt.time() <= business_end
400
401
# Test across multiple timezones
402
utc_time = datetime(2023, 12, 25, 14, 0, tzinfo=gettz('UTC'))
403
timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo']
404
405
for tz in timezones:
406
in_hours = is_business_hours(utc_time, tz)
407
print(f"{tz}: {'Open' if in_hours else 'Closed'}")
408
```
409
410
### DST Transition Safety
411
412
```python
413
from dateutil.tz import gettz, datetime_exists, resolve_imaginary
414
from datetime import datetime, timedelta
415
416
def safe_add_time(dt, delta):
417
"""Add time duration while handling DST transitions safely."""
418
result = dt + delta
419
420
if not datetime_exists(result):
421
result = resolve_imaginary(result)
422
423
return result
424
425
# Example: Add 24 hours during DST transition
426
eastern = gettz('America/New_York')
427
before_transition = datetime(2023, 3, 11, 12, 0, tzinfo=eastern)
428
429
# Naive addition might hit DST gap
430
safe_result = safe_add_time(before_transition, timedelta(hours=24))
431
print(f"Safe result: {safe_result}")
432
```
433
434
## Exception Types
435
436
```python { .api }
437
class DeprecatedTzFormatWarning(Warning):
438
"""Warning raised when parsing deprecated timezone formats."""
439
```
440
441
## Types
442
443
```python { .api }
444
from datetime import datetime, timedelta, tzinfo
445
446
# Core timezone classes inherit from tzinfo
447
class tzutc(tzinfo): ...
448
class tzoffset(tzinfo): ...
449
class tzlocal(tzinfo): ...
450
class tzfile(tzinfo): ...
451
class tzrange(tzinfo): ...
452
class tzstr(tzrange): ...
453
454
# Platform-specific (Windows only)
455
class tzwin(tzinfo): ...
456
class tzwinlocal(tzinfo): ...
457
458
# iCalendar timezone container
459
class tzical:
460
def get(self, name=None) -> tzinfo: ...
461
def keys(self) -> list[str]: ...
462
463
# Utility function return types
464
TzInfo = tzinfo | None
465
```