or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-locales.mddate-time-formatting.mdindex.mdmessage-catalogs.mdnumber-currency-formatting.mdplural-language-data.mdunits-utilities.md

date-time-formatting.mddocs/

0

# Date and Time Formatting

1

2

Comprehensive date, time, and datetime formatting with locale-aware patterns, timezone support, and flexible formatting options. Babel's date formatting leverages CLDR data to provide culturally appropriate date and time representations for different locales.

3

4

## Capabilities

5

6

### Date Formatting

7

8

Format date objects according to locale-specific patterns and conventions.

9

10

```python { .api }

11

def format_date(date, format='medium', locale=None):

12

"""

13

Format a date according to locale conventions.

14

15

Args:

16

date (datetime.date): Date object to format

17

format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern

18

locale (Locale|str): Target locale

19

20

Returns:

21

str: Formatted date string

22

"""

23

```

24

25

Usage example:

26

27

```python

28

from babel.dates import format_date

29

from babel import Locale

30

import datetime

31

32

date = datetime.date(2023, 12, 25)

33

us_locale = Locale('en_US')

34

fr_locale = Locale('fr_FR')

35

36

# Different format lengths

37

print(format_date(date, format='full', locale=us_locale)) # "Monday, December 25, 2023"

38

print(format_date(date, format='long', locale=us_locale)) # "December 25, 2023"

39

print(format_date(date, format='medium', locale=us_locale)) # "Dec 25, 2023"

40

print(format_date(date, format='short', locale=us_locale)) # "12/25/23"

41

42

# French locale

43

print(format_date(date, format='full', locale=fr_locale)) # "lundi 25 décembre 2023"

44

```

45

46

### Time Formatting

47

48

Format time objects with locale-appropriate formatting and timezone support.

49

50

```python { .api }

51

def format_time(time, format='medium', tzinfo=None, locale=None):

52

"""

53

Format a time according to locale conventions.

54

55

Args:

56

time (datetime.time): Time object to format

57

format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern

58

tzinfo (datetime.tzinfo, optional): Timezone info

59

locale (Locale|str): Target locale

60

61

Returns:

62

str: Formatted time string

63

"""

64

```

65

66

Usage example:

67

68

```python

69

from babel.dates import format_time

70

import datetime

71

72

time = datetime.time(14, 30, 45)

73

74

print(format_time(time, format='full')) # "2:30:45 PM"

75

print(format_time(time, format='short')) # "2:30 PM"

76

```

77

78

### DateTime Formatting

79

80

Format datetime objects with combined date and time formatting.

81

82

```python { .api }

83

def format_datetime(datetime, format='medium', tzinfo=None, locale=None):

84

"""

85

Format a datetime according to locale conventions.

86

87

Args:

88

datetime (datetime.datetime): Datetime object to format

89

format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern

90

tzinfo (datetime.tzinfo, optional): Timezone info

91

locale (Locale|str): Target locale

92

93

Returns:

94

str: Formatted datetime string

95

"""

96

```

97

98

Usage example:

99

100

```python

101

from babel.dates import format_datetime

102

import datetime

103

104

dt = datetime.datetime(2023, 12, 25, 14, 30, 45)

105

106

print(format_datetime(dt, format='full')) # "Monday, December 25, 2023 at 2:30:45 PM"

107

print(format_datetime(dt, format='short')) # "12/25/23, 2:30 PM"

108

```

109

110

### Skeleton-Based Formatting

111

112

Flexible date formatting using skeleton patterns that adapt to locale conventions.

113

114

```python { .api }

115

def format_skeleton(skeleton, datetime, tzinfo=None, fuzzy=True, locale=None):

116

"""

117

Format using flexible date skeleton patterns.

118

119

Args:

120

skeleton (str): Skeleton pattern (e.g. 'yMMMd', 'Hms')

121

datetime (datetime.datetime): Datetime to format

122

tzinfo (datetime.tzinfo, optional): Timezone info

123

fuzzy (bool): Whether to allow fuzzy matching

124

locale (Locale|str): Target locale

125

126

Returns:

127

str: Formatted string using best available pattern for skeleton

128

"""

129

```

130

131

Usage example:

132

133

```python

134

from babel.dates import format_skeleton

135

import datetime

136

137

dt = datetime.datetime(2023, 12, 25, 14, 30)

138

139

# Year-Month-Day skeleton

140

print(format_skeleton('yMMMd', dt)) # "Dec 25, 2023"

141

142

# Hour-Minute-Second skeleton

143

print(format_skeleton('Hms', dt)) # "14:30:00"

144

```

145

146

### Relative Time Formatting

147

148

Format time differences in human-readable relative format.

149

150

```python { .api }

151

def format_timedelta(delta, granularity='second', threshold=0.85, add_direction=False, format='long', locale=None):

152

"""

153

Format a timedelta in human-readable relative form.

154

155

Args:

156

delta (datetime.timedelta): Time difference to format

157

granularity (str): Smallest unit to display ('year', 'month', 'week', 'day', 'hour', 'minute', 'second')

158

threshold (float): Threshold for using larger units (0-1)

159

add_direction (bool): Whether to add direction words ('in', 'ago')

160

format (str): Format style ('long', 'short', 'narrow')

161

locale (Locale|str): Target locale

162

163

Returns:

164

str: Human-readable time difference

165

"""

166

```

167

168

Usage example:

169

170

```python

171

from babel.dates import format_timedelta

172

import datetime

173

174

# Different time deltas

175

delta1 = datetime.timedelta(days=2)

176

delta2 = datetime.timedelta(hours=3, minutes=30)

177

delta3 = datetime.timedelta(seconds=45)

178

179

print(format_timedelta(delta1)) # "2 days"

180

print(format_timedelta(delta2, granularity='minute')) # "3 hours"

181

print(format_timedelta(delta3, add_direction=True)) # "in 45 seconds"

182

```

183

184

### Interval Formatting

185

186

Format intervals between two datetime objects.

187

188

```python { .api }

189

def format_interval(start, end, skeleton=None, tzinfo=None, fuzzy=True, locale=None):

190

"""

191

Format an interval between two datetimes.

192

193

Args:

194

start (datetime.datetime): Start of interval

195

end (datetime.datetime): End of interval

196

skeleton (str, optional): Skeleton pattern for formatting

197

tzinfo (datetime.tzinfo, optional): Timezone info

198

fuzzy (bool): Whether to allow fuzzy matching

199

locale (Locale|str): Target locale

200

201

Returns:

202

str: Formatted interval string

203

"""

204

```

205

206

Usage example:

207

208

```python

209

from babel.dates import format_interval

210

import datetime

211

212

start = datetime.datetime(2023, 12, 25, 9, 0)

213

end = datetime.datetime(2023, 12, 25, 17, 30)

214

215

print(format_interval(start, end)) # "Dec 25, 2023, 9:00 AM – 5:30 PM"

216

```

217

218

### Format Pattern Access

219

220

Get locale-specific format patterns for different date/time components.

221

222

```python { .api }

223

def get_date_format(format='medium', locale=default_locale()):

224

"""

225

Get date format pattern for locale.

226

227

Args:

228

format (str): Format type ('full', 'long', 'medium', 'short')

229

locale (Locale|str): Target locale

230

231

Returns:

232

DateTimePattern: Date format pattern object

233

"""

234

235

def get_time_format(format='medium', locale=default_locale()):

236

"""

237

Get time format pattern for locale.

238

239

Args:

240

format (str): Format type ('full', 'long', 'medium', 'short')

241

locale (Locale|str): Target locale

242

243

Returns:

244

DateTimePattern: Time format pattern object

245

"""

246

247

def get_datetime_format(format='medium', locale=default_locale()):

248

"""

249

Get datetime format pattern for locale.

250

251

Args:

252

format (str): Format type ('full', 'long', 'medium', 'short')

253

locale (Locale|str): Target locale

254

255

Returns:

256

DateTimePattern: Datetime format pattern object

257

"""

258

```

259

260

### Display Name Access

261

262

Get localized names for date/time components.

263

264

```python { .api }

265

def get_period_names(width='wide', context='format', locale=default_locale()):

266

"""

267

Get AM/PM period names.

268

269

Args:

270

width (str): Width ('wide', 'abbreviated', 'narrow')

271

context (str): Context ('format', 'stand-alone')

272

locale (Locale|str): Target locale

273

274

Returns:

275

dict: Period names mapping

276

"""

277

278

def get_day_names(width='wide', context='format', locale=default_locale()):

279

"""

280

Get day names (Monday, Tuesday, etc.).

281

282

Args:

283

width (str): Width ('wide', 'abbreviated', 'narrow')

284

context (str): Context ('format', 'stand-alone')

285

locale (Locale|str): Target locale

286

287

Returns:

288

dict: Day names mapping (0=Monday, 6=Sunday)

289

"""

290

291

def get_month_names(width='wide', context='format', locale=default_locale()):

292

"""

293

Get month names.

294

295

Args:

296

width (str): Width ('wide', 'abbreviated', 'narrow')

297

context (str): Context ('format', 'stand-alone')

298

locale (Locale|str): Target locale

299

300

Returns:

301

dict: Month names mapping (1=January, 12=December)

302

"""

303

304

def get_quarter_names(width='wide', context='format', locale=default_locale()):

305

"""

306

Get quarter names (Q1, Q2, etc.).

307

308

Args:

309

width (str): Width ('wide', 'abbreviated', 'narrow')

310

context (str): Context ('format', 'stand-alone')

311

locale (Locale|str): Target locale

312

313

Returns:

314

dict: Quarter names mapping (1=Q1, 4=Q4)

315

"""

316

317

def get_era_names(width='wide', locale=default_locale()):

318

"""

319

Get era names (BC, AD, etc.).

320

321

Args:

322

width (str): Width ('wide', 'abbreviated', 'narrow')

323

locale (Locale|str): Target locale

324

325

Returns:

326

dict: Era names mapping

327

"""

328

```

329

330

### Timezone Support

331

332

Timezone handling and display functions.

333

334

```python { .api }

335

def get_timezone(zone):

336

"""

337

Get timezone object by identifier.

338

339

Args:

340

zone (str|datetime.tzinfo|None): Timezone identifier or object

341

342

Returns:

343

datetime.tzinfo: Timezone object

344

"""

345

346

def get_timezone_name(dt_or_tzinfo, width='long', uncommon=False, locale=default_locale()):

347

"""

348

Get timezone display name.

349

350

Args:

351

dt_or_tzinfo (datetime.datetime|datetime.tzinfo): Datetime or timezone

352

width (str): Width ('long', 'short')

353

uncommon (bool): Whether to include uncommon timezones

354

locale (Locale|str): Target locale

355

356

Returns:

357

str: Timezone display name

358

"""

359

360

def get_timezone_location(dt_or_tzinfo, locale=default_locale()):

361

"""

362

Get timezone location name.

363

364

Args:

365

dt_or_tzinfo (datetime.datetime|datetime.tzinfo): Datetime or timezone

366

locale (Locale|str): Target locale

367

368

Returns:

369

str: Location-based timezone name

370

"""

371

372

def get_timezone_gmt(datetime, width='long', locale=default_locale()):

373

"""

374

Get GMT offset format for timezone.

375

376

Args:

377

datetime (datetime.datetime): Datetime with timezone

378

width (str): Width ('long', 'short')

379

locale (Locale|str): Target locale

380

381

Returns:

382

str: GMT offset string (e.g. "GMT-05:00")

383

"""

384

```

385

386

### Date/Time Parsing

387

388

Parse date and time strings according to locale conventions.

389

390

```python { .api }

391

def parse_date(string, locale=default_locale()):

392

"""

393

Parse a date string according to locale.

394

395

Args:

396

string (str): Date string to parse

397

locale (Locale|str): Source locale

398

399

Returns:

400

datetime.date: Parsed date object

401

402

Raises:

403

ParseError: If parsing fails

404

"""

405

406

def parse_time(string, locale=default_locale()):

407

"""

408

Parse a time string according to locale.

409

410

Args:

411

string (str): Time string to parse

412

locale (Locale|str): Source locale

413

414

Returns:

415

datetime.time: Parsed time object

416

417

Raises:

418

ParseError: If parsing fails

419

"""

420

421

def parse_pattern(pattern):

422

"""

423

Parse a date/time format pattern.

424

425

Args:

426

pattern (str): Format pattern string

427

428

Returns:

429

DateTimePattern: Parsed pattern object

430

"""

431

```

432

433

### Pattern and Format Classes

434

435

```python { .api }

436

class DateTimePattern:

437

"""Represents a parsed date/time format pattern."""

438

439

def format(self, datetime, tzinfo=None):

440

"""

441

Format a datetime using this pattern.

442

443

Args:

444

datetime (datetime.datetime): Datetime to format

445

tzinfo (datetime.tzinfo, optional): Timezone info

446

447

Returns:

448

str: Formatted string

449

"""

450

451

class DateTimeFormat:

452

"""Formatter for date/time values using patterns."""

453

454

def __init__(self, pattern, locale):

455

"""

456

Initialize formatter with pattern and locale.

457

458

Args:

459

pattern (str|DateTimePattern): Format pattern

460

locale (Locale|str): Target locale

461

"""

462

```

463

464

### Constants

465

466

```python { .api }

467

UTC: datetime.tzinfo

468

"""UTC timezone object"""

469

470

LOCALTZ: datetime.tzinfo

471

"""Local timezone object"""

472

```

473

474

## Exception Classes

475

476

```python { .api }

477

class ParseError(ValueError):

478

"""Raised when date/time parsing fails."""

479

```