0
# Formatting and Localization
1
2
Multiple output formats and localization support for human-readable datetime representation. Pendulum provides extensive formatting capabilities including standard formats, custom patterns, and localized output across 200+ languages and cultures.
3
4
## Capabilities
5
6
### Format Functions
7
8
Module-level functions for formatting temporal differences and managing locales.
9
10
```python { .api }
11
def format_diff(
12
diff: Duration,
13
is_now: bool = True,
14
absolute: bool = False,
15
locale: str | None = None
16
) -> str:
17
"""
18
Format duration in human-readable form.
19
20
Parameters:
21
- diff: Duration to format
22
- is_now: Whether to include "ago"/"from now" context
23
- absolute: Whether to omit directional indicators
24
- locale: Locale for formatting
25
26
Returns:
27
str: Human-readable difference (e.g., "2 hours ago")
28
"""
29
30
def set_locale(name: str) -> None:
31
"""
32
Set global default locale.
33
34
Parameters:
35
- name: Locale name (e.g., 'en', 'fr', 'es', 'de')
36
"""
37
38
def get_locale() -> str:
39
"""
40
Get current global locale.
41
42
Returns:
43
str: Current locale name
44
"""
45
46
def locale(name: str):
47
"""
48
Get Locale instance for specific locale.
49
50
Parameters:
51
- name: Locale name
52
53
Returns:
54
Locale: Locale instance for the specified language/culture
55
"""
56
```
57
58
### Week Configuration
59
60
Functions for configuring week start/end days globally.
61
62
```python { .api }
63
def week_starts_at(wday: WeekDay) -> None:
64
"""
65
Set global week start day.
66
67
Parameters:
68
- wday: WeekDay enum value for week start
69
"""
70
71
def week_ends_at(wday: WeekDay) -> None:
72
"""
73
Set global week end day.
74
75
Parameters:
76
- wday: WeekDay enum value for week end
77
"""
78
```
79
80
### DateTime Formatting Methods
81
82
Methods available on DateTime instances for various output formats.
83
84
```python { .api }
85
class DateTime:
86
def format(self, fmt: str, locale: str | None = None) -> str:
87
"""
88
Format using custom format string.
89
90
Parameters:
91
- fmt: Format pattern (e.g., 'YYYY-MM-DD HH:mm:ss')
92
- locale: Locale for formatting
93
94
Returns:
95
str: Formatted datetime string
96
"""
97
98
def for_json(self) -> str:
99
"""
100
Format for JSON serialization (ISO format).
101
102
Returns:
103
str: ISO 8601 formatted string
104
"""
105
106
def diff_for_humans(
107
self,
108
other: DateTime | None = None,
109
absolute: bool = False,
110
locale: str | None = None
111
) -> str:
112
"""
113
Get human-readable difference description.
114
115
Parameters:
116
- other: Other DateTime (defaults to now)
117
- absolute: Whether to omit ago/from now
118
- locale: Locale for formatting
119
120
Returns:
121
str: Human-readable difference
122
"""
123
124
def to_time_string(self) -> str:
125
"""Format as HH:mm:ss"""
126
127
def to_datetime_string(self) -> str:
128
"""Format as YYYY-MM-DD HH:mm:ss"""
129
130
def to_day_datetime_string(self) -> str:
131
"""Format as "Wed, Dec 25, 2013 4:03 PM" """
132
133
def to_atom_string(self) -> str:
134
"""Format as ATOM (RFC 3339)"""
135
136
def to_cookie_string(self) -> str:
137
"""Format for HTTP cookies"""
138
139
def to_iso8601_string(self) -> str:
140
"""Format as ISO 8601"""
141
142
def to_rfc822_string(self) -> str:
143
"""Format as RFC 822"""
144
145
def to_rfc850_string(self) -> str:
146
"""Format as RFC 850"""
147
148
def to_rfc1036_string(self) -> str:
149
"""Format as RFC 1036"""
150
151
def to_rfc1123_string(self) -> str:
152
"""Format as RFC 1123"""
153
154
def to_rfc2822_string(self) -> str:
155
"""Format as RFC 2822"""
156
157
def to_rfc3339_string(self) -> str:
158
"""Format as RFC 3339"""
159
160
def to_rss_string(self) -> str:
161
"""Format for RSS feeds"""
162
163
def to_w3c_string(self) -> str:
164
"""Format as W3C (ISO 8601)"""
165
```
166
167
### Date and Time Formatting Methods
168
169
Formatting methods for Date and Time classes.
170
171
```python { .api }
172
class Date:
173
def format(self, fmt: str, locale: str | None = None) -> str:
174
"""Format using custom format string"""
175
176
def to_date_string(self) -> str:
177
"""Format as YYYY-MM-DD"""
178
179
def to_formatted_date_string(self) -> str:
180
"""Format as "Dec 25, 2013" """
181
182
def diff_for_humans(
183
self,
184
other: Date | None = None,
185
absolute: bool = False,
186
locale: str | None = None
187
) -> str:
188
"""Get human-readable difference description"""
189
190
class Time:
191
def format(self, fmt: str, locale: str | None = None) -> str:
192
"""Format using custom format string"""
193
194
def diff_for_humans(
195
self,
196
other: Time | None = None,
197
absolute: bool = False,
198
locale: str | None = None
199
) -> str:
200
"""Get human-readable difference description"""
201
```
202
203
### Duration Formatting Methods
204
205
Formatting methods for Duration and Interval classes.
206
207
```python { .api }
208
class Duration:
209
def in_words(self, locale: str | None = None, separator: str = " ") -> str:
210
"""
211
Human-readable duration description.
212
213
Parameters:
214
- locale: Locale for formatting
215
- separator: Separator between components
216
217
Returns:
218
str: Human-readable duration
219
"""
220
221
class Interval(Duration):
222
"""Interval inherits in_words() method from Duration"""
223
```
224
225
### Formatter Class
226
227
Advanced formatting and parsing capabilities.
228
229
```python { .api }
230
class Formatter:
231
def format(
232
self,
233
dt: DateTime,
234
fmt: str,
235
locale: str | None = None
236
) -> str:
237
"""
238
Format datetime with pattern.
239
240
Parameters:
241
- dt: DateTime to format
242
- fmt: Format pattern
243
- locale: Locale for formatting
244
245
Returns:
246
str: Formatted string
247
"""
248
249
def parse(
250
self,
251
string: str,
252
fmt: str,
253
now: DateTime,
254
locale: str | None = None
255
) -> dict:
256
"""
257
Parse string with pattern.
258
259
Parameters:
260
- string: String to parse
261
- fmt: Format pattern
262
- now: Reference DateTime for relative parsing
263
- locale: Locale for parsing
264
265
Returns:
266
dict: Parsed components
267
"""
268
```
269
270
## Format Patterns
271
272
Common format patterns for custom formatting:
273
274
```python { .api }
275
# Date patterns
276
YYYY # 4-digit year (2024)
277
YY # 2-digit year (24)
278
MMMM # Full month name (January)
279
MMM # Short month name (Jan)
280
MM # 2-digit month (01)
281
M # Month (1)
282
DD # 2-digit day (01)
283
D # Day (1)
284
Do # Ordinal day (1st, 2nd)
285
286
# Time patterns
287
HH # 24-hour (00-23)
288
H # 24-hour (0-23)
289
hh # 12-hour (01-12)
290
h # 12-hour (1-12)
291
mm # Minutes (00-59)
292
m # Minutes (0-59)
293
ss # Seconds (00-59)
294
s # Seconds (0-59)
295
S # Deciseconds (0-9)
296
SS # Centiseconds (00-99)
297
SSS # Milliseconds (000-999)
298
SSSS # Microseconds (000000-999999)
299
A # AM/PM
300
a # am/pm
301
302
# Weekday patterns
303
dddd # Full weekday (Monday)
304
ddd # Short weekday (Mon)
305
dd # Min weekday (Mo)
306
d # Weekday number (1)
307
308
# Timezone patterns
309
Z # Offset (+05:00)
310
ZZ # Compact offset (+0500)
311
zz # Timezone name (EST)
312
```
313
314
## Usage Examples
315
316
### Custom Formatting
317
318
```python
319
import pendulum
320
321
dt = pendulum.datetime(2024, 3, 15, 14, 30, 45, tz='Europe/Paris')
322
323
# Custom format patterns
324
print(dt.format('YYYY-MM-DD HH:mm:ss')) # 2024-03-15 14:30:45
325
print(dt.format('MMMM Do, YYYY')) # March 15th, 2024
326
print(dt.format('dddd, MMMM DD, YYYY')) # Friday, March 15, 2024
327
print(dt.format('h:mm A')) # 2:30 PM
328
print(dt.format('HH:mm:ss Z')) # 14:30:45 +01:00
329
330
# Localized formatting
331
print(dt.format('MMMM Do, YYYY', locale='fr')) # mars 15e, 2024
332
print(dt.format('MMMM Do, YYYY', locale='es')) # marzo 15º, 2024
333
print(dt.format('dddd, MMMM DD', locale='de')) # Freitag, März 15
334
```
335
336
### Standard Format Methods
337
338
```python
339
import pendulum
340
341
dt = pendulum.now('UTC')
342
343
# Standard format methods
344
print(dt.to_time_string()) # 14:30:45
345
print(dt.to_datetime_string()) # 2024-03-15 14:30:45
346
print(dt.to_day_datetime_string()) # Fri, Mar 15, 2024 2:30 PM
347
print(dt.to_iso8601_string()) # 2024-03-15T14:30:45+00:00
348
print(dt.to_rfc2822_string()) # Fri, 15 Mar 2024 14:30:45 +0000
349
print(dt.to_atom_string()) # 2024-03-15T14:30:45+00:00
350
351
# Date formatting
352
date = pendulum.date(2024, 3, 15)
353
print(date.to_date_string()) # 2024-03-15
354
print(date.to_formatted_date_string()) # Mar 15, 2024
355
356
# JSON serialization
357
print(dt.for_json()) # 2024-03-15T14:30:45+00:00
358
```
359
360
### Human-Readable Differences
361
362
```python
363
import pendulum
364
365
now = pendulum.now()
366
367
# Past times
368
past_hour = now.subtract(hours=1)
369
past_day = now.subtract(days=1)
370
past_month = now.subtract(months=1)
371
372
print(past_hour.diff_for_humans()) # an hour ago
373
print(past_day.diff_for_humans()) # a day ago
374
print(past_month.diff_for_humans()) # a month ago
375
376
# Future times
377
future_hour = now.add(hours=2)
378
future_week = now.add(weeks=1)
379
380
print(future_hour.diff_for_humans()) # in 2 hours
381
print(future_week.diff_for_humans()) # in a week
382
383
# Absolute differences (no ago/from now)
384
print(past_hour.diff_for_humans(absolute=True)) # an hour
385
386
# Compared to specific time
387
yesterday = now.subtract(days=1)
388
print(now.diff_for_humans(yesterday)) # a day after
389
```
390
391
### Localized Human-Readable Output
392
393
```python
394
import pendulum
395
396
# Set global locale
397
pendulum.set_locale('fr')
398
dt = pendulum.now().subtract(hours=2)
399
print(dt.diff_for_humans()) # il y a 2 heures
400
401
# Use specific locale
402
dt = pendulum.now().subtract(days=3)
403
print(dt.diff_for_humans(locale='es')) # hace 3 días
404
print(dt.diff_for_humans(locale='de')) # vor 3 Tagen
405
print(dt.diff_for_humans(locale='it')) # 3 giorni fa
406
407
# Restore English
408
pendulum.set_locale('en')
409
print(dt.diff_for_humans()) # 3 days ago
410
411
# Duration formatting with locale
412
duration = pendulum.duration(years=1, months=2, days=5)
413
print(duration.in_words()) # 1 year 2 months 5 days
414
print(duration.in_words(locale='fr')) # 1 an 2 mois 5 jours
415
print(duration.in_words(locale='es')) # 1 año 2 meses 5 días
416
```
417
418
### Working with Multiple Locales
419
420
```python
421
import pendulum
422
423
dt = pendulum.datetime(2024, 12, 25, 18, 30)
424
425
# Different locale outputs
426
locales = ['en', 'fr', 'es', 'de', 'it', 'pt', 'ru', 'ja', 'zh']
427
428
for loc in locales:
429
formatted = dt.format('MMMM Do, YYYY - dddd', locale=loc)
430
print(f"{loc}: {formatted}")
431
432
# Example output:
433
# en: December 25th, 2024 - Wednesday
434
# fr: décembre 25e, 2024 - mercredi
435
# es: diciembre 25º, 2024 - miércoles
436
# de: Dezember 25., 2024 - Mittwoch
437
```
438
439
### Week Configuration
440
441
```python
442
import pendulum
443
444
# Default week starts on Monday
445
dt = pendulum.date(2024, 3, 15) # Friday
446
week_start = dt.start_of('week')
447
print(f"Week starts: {week_start}") # Monday
448
449
# Change global week start to Sunday
450
pendulum.week_starts_at(pendulum.SUNDAY)
451
week_start_sunday = dt.start_of('week')
452
print(f"Week starts (Sunday): {week_start_sunday}") # Sunday
453
454
# Change week end
455
pendulum.week_ends_at(pendulum.SATURDAY)
456
week_end = dt.end_of('week')
457
print(f"Week ends: {week_end}") # Saturday
458
459
# Reset to defaults
460
pendulum.week_starts_at(pendulum.MONDAY)
461
pendulum.week_ends_at(pendulum.SUNDAY)
462
```
463
464
### Advanced Formatting with Formatter
465
466
```python
467
import pendulum
468
469
formatter = pendulum.Formatter()
470
dt = pendulum.now()
471
472
# Direct formatting
473
formatted = formatter.format(dt, 'YYYY-MM-DD [at] HH:mm')
474
print(formatted) # 2024-03-15 at 14:30
475
476
# Parsing with format
477
now_ref = pendulum.now()
478
parsed_parts = formatter.parse('2024-12-25 18:30', 'YYYY-MM-DD HH:mm', now_ref)
479
print(parsed_parts) # Dict with parsed components
480
481
# Create datetime from parsed parts
482
if parsed_parts['tz'] is None:
483
parsed_parts['tz'] = 'UTC'
484
parsed_dt = pendulum.datetime(**parsed_parts)
485
print(parsed_dt)
486
```
487
488
### Format Combinations
489
490
```python
491
import pendulum
492
493
dt = pendulum.datetime(2024, 3, 15, 14, 30, 45, 123456)
494
495
# Combining different format elements
496
formats = [
497
'YYYY-MM-DD HH:mm:ss.SSSS', # 2024-03-15 14:30:45.1234
498
'ddd, MMM Do YYYY [at] h:mm A', # Fri, Mar 15th 2024 at 2:30 PM
499
'dddd the Do [of] MMMM, YYYY', # Friday the 15th of March, 2024
500
'HH:mm:ss Z [on] YYYY-MM-DD', # 14:30:45 +00:00 on 2024-03-15
501
'[Week] W [of] YYYY', # Week 11 of 2024
502
]
503
504
for fmt in formats:
505
print(f"{fmt:<35} → {dt.format(fmt)}")
506
507
# Literal text in square brackets
508
print(dt.format('[Today is] dddd')) # Today is Friday
509
print(dt.format('YYYY [年] MM [月] DD [日]')) # 2024 年 03 月 15 日
510
```