0
# Timezone Management
1
2
Comprehensive timezone handling with IANA database support. Pendulum provides robust timezone functionality including timezone creation, conversion, DST handling, and local timezone management for testing scenarios.
3
4
## Capabilities
5
6
### Timezone Creation
7
8
Functions for creating various types of timezone objects.
9
10
```python { .api }
11
def timezone(name: str | int) -> Timezone | FixedTimezone:
12
"""
13
Create timezone from name or offset.
14
15
Parameters:
16
- name: IANA timezone name (e.g., 'Europe/Paris') or UTC offset in hours
17
18
Returns:
19
Timezone | FixedTimezone: Timezone object
20
"""
21
22
23
def local_timezone() -> Timezone:
24
"""
25
Get system local timezone.
26
27
Returns:
28
Timezone: Local timezone object
29
"""
30
```
31
32
### Timezone Management
33
34
Functions for managing timezone settings and querying available timezones.
35
36
```python { .api }
37
def set_local_timezone(tz: str | Timezone) -> None:
38
"""
39
Set local timezone for testing purposes (persistent).
40
41
Parameters:
42
- tz: Timezone name or Timezone object
43
"""
44
45
def test_local_timezone(tz: str | Timezone):
46
"""
47
Context manager to temporarily set local timezone.
48
49
Parameters:
50
- tz: Timezone name or Timezone object
51
52
Usage:
53
with pendulum.test_local_timezone('Europe/Paris'):
54
# Local timezone is temporarily Paris
55
dt = pendulum.now('local')
56
"""
57
58
def timezones() -> set[str]:
59
"""
60
Get set of all available IANA timezone names.
61
62
Returns:
63
set[str]: Set of timezone names
64
"""
65
```
66
67
### Timezone Class
68
69
IANA timezone representation with dynamic DST handling.
70
71
```python { .api }
72
class Timezone:
73
def __init__(self, key: str):
74
"""
75
Create timezone from IANA key.
76
77
Parameters:
78
- key: IANA timezone name (e.g., 'America/New_York')
79
"""
80
81
def convert(
82
self,
83
dt: DateTime,
84
raise_on_unknown_times: bool = False
85
) -> DateTime:
86
"""
87
Convert DateTime to this timezone.
88
89
Parameters:
90
- dt: DateTime to convert
91
- raise_on_unknown_times: Raise exception for ambiguous times
92
93
Returns:
94
DateTime: DateTime in this timezone
95
"""
96
97
def datetime(
98
self,
99
year: int,
100
month: int,
101
day: int,
102
hour: int = 0,
103
minute: int = 0,
104
second: int = 0,
105
microsecond: int = 0
106
) -> DateTime:
107
"""
108
Create DateTime in this timezone.
109
110
Parameters:
111
- year: Year
112
- month: Month
113
- day: Day
114
- hour: Hour
115
- minute: Minute
116
- second: Second
117
- microsecond: Microsecond
118
119
Returns:
120
DateTime: DateTime in this timezone
121
"""
122
123
@property
124
def name(self) -> str:
125
"""IANA timezone name"""
126
```
127
128
### FixedTimezone Class
129
130
Fixed UTC offset timezone representation.
131
132
```python { .api }
133
class FixedTimezone:
134
def __init__(self, offset: int, name: str | None = None):
135
"""
136
Create fixed offset timezone.
137
138
Parameters:
139
- offset: UTC offset in seconds
140
- name: Optional timezone name
141
"""
142
143
def convert(
144
self,
145
dt: DateTime,
146
raise_on_unknown_times: bool = False
147
) -> DateTime:
148
"""
149
Convert DateTime to this timezone.
150
151
Parameters:
152
- dt: DateTime to convert
153
- raise_on_unknown_times: Ignored for fixed timezones
154
155
Returns:
156
DateTime: DateTime in this timezone
157
"""
158
159
def datetime(
160
self,
161
year: int,
162
month: int,
163
day: int,
164
hour: int = 0,
165
minute: int = 0,
166
second: int = 0,
167
microsecond: int = 0
168
) -> DateTime:
169
"""
170
Create DateTime in this timezone.
171
172
Returns:
173
DateTime: DateTime in this timezone
174
"""
175
176
def utcoffset(self, dt) -> timedelta:
177
"""
178
Get UTC offset as timedelta.
179
180
Parameters:
181
- dt: DateTime (ignored for fixed offset)
182
183
Returns:
184
timedelta: UTC offset
185
"""
186
187
def dst(self, dt) -> timedelta:
188
"""
189
Get DST offset (always zero for fixed timezone).
190
191
Parameters:
192
- dt: DateTime (ignored)
193
194
Returns:
195
timedelta: Always timedelta(0)
196
"""
197
198
def tzname(self, dt) -> str:
199
"""
200
Get timezone name.
201
202
Parameters:
203
- dt: DateTime (ignored)
204
205
Returns:
206
str: Timezone name
207
"""
208
209
@property
210
def name(self) -> str:
211
"""Timezone name"""
212
213
@property
214
def offset(self) -> int:
215
"""UTC offset in seconds"""
216
```
217
218
### Special Timezone Constants
219
220
Pre-defined timezone objects for common use cases.
221
222
```python { .api }
223
UTC: FixedTimezone # UTC timezone (offset 0)
224
```
225
226
## Usage Examples
227
228
### Creating and Using Timezones
229
230
```python
231
import pendulum
232
233
# Create timezones by name
234
paris_tz = pendulum.timezone('Europe/Paris')
235
tokyo_tz = pendulum.timezone('Asia/Tokyo')
236
utc_tz = pendulum.timezone('UTC')
237
238
# Create timezone from UTC offset (hours)
239
plus_5_tz = pendulum.timezone(5) # +5 hours
240
minus_8_tz = pendulum.timezone(-8) # -8 hours
241
242
# Create fixed offset timezone through timezone() with integer offset
243
fixed_tz = pendulum.timezone(5) # +5 hours
244
245
# Use predefined UTC
246
utc_dt = pendulum.now(pendulum.UTC)
247
248
print(f"Paris timezone: {paris_tz.name}")
249
print(f"Fixed timezone offset: {fixed_tz.offset} seconds")
250
```
251
252
### Converting Between Timezones
253
254
```python
255
import pendulum
256
257
# Create DateTime in one timezone
258
utc_dt = pendulum.now('UTC')
259
print(f"UTC: {utc_dt}")
260
261
# Convert to different timezones
262
paris_dt = utc_dt.in_timezone('Europe/Paris')
263
tokyo_dt = utc_dt.in_timezone('Asia/Tokyo')
264
local_dt = utc_dt.in_timezone('local')
265
266
print(f"Paris: {paris_dt}")
267
print(f"Tokyo: {tokyo_dt}")
268
print(f"Local: {local_dt}")
269
270
# Using timezone objects
271
paris_tz = pendulum.timezone('Europe/Paris')
272
converted = utc_dt.in_timezone(paris_tz)
273
print(f"Converted: {converted}")
274
275
# Direct conversion with timezone.convert()
276
converted2 = paris_tz.convert(utc_dt)
277
print(f"Direct convert: {converted2}")
278
```
279
280
### Creating DateTimes in Specific Timezones
281
282
```python
283
import pendulum
284
285
# Create DateTime directly in timezone
286
paris_dt = pendulum.datetime(2024, 6, 15, 14, 30, tz='Europe/Paris')
287
tokyo_dt = pendulum.datetime(2024, 6, 15, 14, 30, tz='Asia/Tokyo')
288
289
# Using timezone objects
290
paris_tz = pendulum.timezone('Europe/Paris')
291
tz_dt = paris_tz.datetime(2024, 6, 15, 14, 30)
292
293
# Using module-level functions
294
local_dt = pendulum.local(2024, 6, 15, 14, 30) # Local timezone
295
utc_dt = pendulum.datetime(2024, 6, 15, 14, 30) # UTC (default)
296
297
print(f"Paris: {paris_dt} (offset: {paris_dt.offset_hours}h)")
298
print(f"Tokyo: {tokyo_dt} (offset: {tokyo_dt.offset_hours}h)")
299
print(f"From timezone object: {tz_dt}")
300
```
301
302
### Working with DST Transitions
303
304
```python
305
import pendulum
306
307
# DST transition examples
308
# Spring forward (2024-03-31 in Europe/Paris)
309
paris_tz = pendulum.timezone('Europe/Paris')
310
311
# Before DST transition (CET = UTC+1)
312
before_dst = paris_tz.datetime(2024, 3, 31, 1, 30)
313
print(f"Before DST: {before_dst} (DST: {before_dst.is_dst()})")
314
315
# After DST transition (CEST = UTC+2)
316
after_dst = paris_tz.datetime(2024, 3, 31, 3, 30)
317
print(f"After DST: {after_dst} (DST: {after_dst.is_dst()})")
318
319
# Check DST status
320
summer_dt = paris_tz.datetime(2024, 7, 15, 12, 0)
321
winter_dt = paris_tz.datetime(2024, 1, 15, 12, 0)
322
323
print(f"Summer DST: {summer_dt.is_dst()}") # True
324
print(f"Winter DST: {winter_dt.is_dst()}") # False
325
```
326
327
### Handling Ambiguous Times
328
329
```python
330
import pendulum
331
332
# During DST transitions, some times can be ambiguous
333
# Fall back transition (2024-10-27 in Europe/Paris)
334
paris_tz = pendulum.timezone('Europe/Paris')
335
336
# This time occurs twice during fall-back
337
try:
338
# By default, Pendulum handles ambiguous times gracefully
339
ambiguous_dt = paris_tz.datetime(2024, 10, 27, 2, 30)
340
print(f"Ambiguous time handled: {ambiguous_dt}")
341
except Exception as e:
342
print(f"Error: {e}")
343
344
# Explicitly raise on unknown times
345
try:
346
strict_dt = paris_tz.datetime(
347
2024, 10, 27, 2, 30,
348
raise_on_unknown_times=True
349
)
350
except Exception as e:
351
print(f"Strict mode error: {e}")
352
353
# Use fold parameter for disambiguation
354
dt_fold_0 = pendulum.datetime(
355
2024, 10, 27, 2, 30,
356
tz='Europe/Paris',
357
fold=0 # First occurrence
358
)
359
dt_fold_1 = pendulum.datetime(
360
2024, 10, 27, 2, 30,
361
tz='Europe/Paris',
362
fold=1 # Second occurrence
363
)
364
365
print(f"Fold 0: {dt_fold_0}")
366
print(f"Fold 1: {dt_fold_1}")
367
```
368
369
### Local Timezone Management
370
371
```python
372
import pendulum
373
374
# Get current local timezone
375
local_tz = pendulum.local_timezone()
376
print(f"System local timezone: {local_tz.name}")
377
378
# Create DateTime in local timezone
379
local_now = pendulum.now('local')
380
print(f"Local now: {local_now}")
381
382
# Temporarily change local timezone for testing
383
with pendulum.test_local_timezone('Asia/Tokyo'):
384
temp_local = pendulum.now('local')
385
print(f"Temporary local (Tokyo): {temp_local}")
386
387
# Local timezone restored after context
388
restored = pendulum.now('local')
389
print(f"Restored local: {restored}")
390
391
# Permanently set local timezone (for testing)
392
pendulum.set_local_timezone('Europe/Paris')
393
new_local = pendulum.now('local')
394
print(f"New local (Paris): {new_local}")
395
```
396
397
### Querying Available Timezones
398
399
```python
400
import pendulum
401
402
# Get all available timezones
403
all_timezones = pendulum.timezones()
404
print(f"Total timezones: {len(all_timezones)}")
405
406
# Filter for specific regions
407
europe_timezones = {tz for tz in all_timezones if tz.startswith('Europe/')}
408
america_timezones = {tz for tz in all_timezones if tz.startswith('America/')}
409
410
print(f"Europe timezones: {len(europe_timezones)}")
411
print(f"America timezones: {len(america_timezones)}")
412
413
# Some examples
414
print("Some Europe timezones:")
415
for tz in sorted(list(europe_timezones)[:5]):
416
print(f" {tz}")
417
418
# Check if timezone exists
419
tz_name = 'Europe/London'
420
if tz_name in all_timezones:
421
london_tz = pendulum.timezone(tz_name)
422
print(f"London timezone: {london_tz.name}")
423
```
424
425
### Fixed Offset Timezones
426
427
```python
428
import pendulum
429
430
# Create fixed offset timezones using FixedTimezone class directly
431
from pendulum.tz.timezone import FixedTimezone
432
plus_5_30 = FixedTimezone(int(5.5 * 3600)) # +05:30 (India)
433
minus_3_30 = FixedTimezone(int(-3.5 * 3600)) # -03:30 (Newfoundland)
434
435
# Create DateTimes with fixed offsets
436
india_dt = pendulum.datetime(2024, 6, 15, 14, 30, tz=plus_5_30)
437
nfld_dt = pendulum.datetime(2024, 6, 15, 14, 30, tz=minus_3_30)
438
439
print(f"India time: {india_dt}")
440
print(f"Newfoundland time: {nfld_dt}")
441
442
# Fixed offset properties
443
print(f"India offset: {plus_5_30.offset} seconds")
444
print(f"India offset hours: {plus_5_30.offset / 3600}")
445
446
# DST is always 0 for fixed timezones
447
print(f"DST offset: {plus_5_30.dst(None)}")
448
```