or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

date-time-components.mddatetime-operations.mdduration-intervals.mdformatting-localization.mdindex.mdtesting-utilities.mdtimezone-management.md

datetime-operations.mddocs/

0

# DateTime Operations

1

2

Core datetime creation, manipulation, and timezone handling functionality. The DateTime class provides timezone-aware datetime objects with extensive methods for creation, conversion, arithmetic, and comparison operations.

3

4

## Capabilities

5

6

### DateTime Creation

7

8

Functions for creating DateTime instances from various sources including current time, specific components, strings, and timestamps.

9

10

```python { .api }

11

def now(tz: str | Timezone | None = None) -> DateTime:

12

"""

13

Get current DateTime in specified timezone.

14

15

Parameters:

16

- tz: Timezone name, Timezone object, or None for UTC

17

18

Returns:

19

DateTime: Current datetime in specified timezone

20

"""

21

22

def datetime(

23

year: int,

24

month: int,

25

day: int,

26

hour: int = 0,

27

minute: int = 0,

28

second: int = 0,

29

microsecond: int = 0,

30

tz: str | Timezone | None = None,

31

fold: int = 1,

32

raise_on_unknown_times: bool = False

33

) -> DateTime:

34

"""

35

Create DateTime from components.

36

37

Parameters:

38

- year: Year (1-9999)

39

- month: Month (1-12)

40

- day: Day (1-31)

41

- hour: Hour (0-23)

42

- minute: Minute (0-59)

43

- second: Second (0-59)

44

- microsecond: Microsecond (0-999999)

45

- tz: Timezone (defaults to UTC)

46

- fold: DST fold handling (0 or 1)

47

- raise_on_unknown_times: Raise exception for ambiguous times

48

49

Returns:

50

DateTime: New DateTime instance

51

"""

52

53

def local(

54

year: int,

55

month: int,

56

day: int,

57

hour: int = 0,

58

minute: int = 0,

59

second: int = 0,

60

microsecond: int = 0

61

) -> DateTime:

62

"""

63

Create DateTime in local timezone.

64

65

Returns:

66

DateTime: DateTime in system local timezone

67

"""

68

69

def naive(

70

year: int,

71

month: int,

72

day: int,

73

hour: int = 0,

74

minute: int = 0,

75

second: int = 0,

76

microsecond: int = 0,

77

fold: int = 1

78

) -> DateTime:

79

"""

80

Create naive DateTime (no timezone).

81

82

Returns:

83

DateTime: Naive DateTime instance

84

"""

85

86

def today(tz: str | Timezone = "local") -> DateTime:

87

"""

88

Create DateTime for today at start of day.

89

90

Returns:

91

DateTime: Today at 00:00:00

92

"""

93

94

def tomorrow(tz: str | Timezone = "local") -> DateTime:

95

"""

96

Create DateTime for tomorrow at start of day.

97

98

Returns:

99

DateTime: Tomorrow at 00:00:00

100

"""

101

102

def yesterday(tz: str | Timezone = "local") -> DateTime:

103

"""

104

Create DateTime for yesterday at start of day.

105

106

Returns:

107

DateTime: Yesterday at 00:00:00

108

"""

109

```

110

111

### String Parsing

112

113

Functions for parsing datetime strings in various formats.

114

115

```python { .api }

116

def parse(string: str, **options) -> DateTime | Date | Time | Duration:

117

"""

118

Parse datetime string automatically detecting format.

119

120

Parameters:

121

- string: Datetime string to parse

122

- **options: Additional parsing options

123

124

Returns:

125

DateTime | Date | Time | Duration: Parsed temporal object

126

"""

127

128

def from_format(

129

string: str,

130

fmt: str,

131

tz: str | Timezone = 'UTC',

132

locale: str | None = None

133

) -> DateTime:

134

"""

135

Parse datetime string with specific format.

136

137

Parameters:

138

- string: Datetime string to parse

139

- fmt: Format string (e.g., 'YYYY-MM-DD HH:mm:ss')

140

- tz: Timezone for result

141

- locale: Locale for parsing

142

143

Returns:

144

DateTime: Parsed DateTime

145

"""

146

147

def from_timestamp(timestamp: int | float, tz: str | Timezone = 'UTC') -> DateTime:

148

"""

149

Create DateTime from Unix timestamp.

150

151

Parameters:

152

- timestamp: Unix timestamp (seconds since epoch)

153

- tz: Timezone for result

154

155

Returns:

156

DateTime: DateTime from timestamp

157

"""

158

```

159

160

### Object Conversion

161

162

Functions for converting standard datetime objects to Pendulum objects.

163

164

```python { .api }

165

def instance(obj, tz: str | Timezone | None = None) -> DateTime | Date | Time:

166

"""

167

Create Pendulum object from standard datetime/date/time.

168

169

Parameters:

170

- obj: datetime, date, or time object

171

- tz: Timezone for DateTime objects

172

173

Returns:

174

DateTime | Date | Time: Corresponding Pendulum object

175

"""

176

```

177

178

### DateTime Class Methods

179

180

Class methods available on the DateTime class for various creation patterns.

181

182

```python { .api }

183

class DateTime:

184

@classmethod

185

def create(

186

cls,

187

year: int,

188

month: int,

189

day: int,

190

hour: int = 0,

191

minute: int = 0,

192

second: int = 0,

193

microsecond: int = 0,

194

tz: str | Timezone | None = None,

195

fold: int = 1,

196

raise_on_unknown_times: bool = False

197

) -> DateTime:

198

"""Create DateTime from components (same as module-level datetime())"""

199

200

@classmethod

201

def now(cls, tz: str | Timezone | None = None) -> DateTime:

202

"""Get current DateTime (same as module-level now())"""

203

204

@classmethod

205

def utcnow(cls) -> DateTime:

206

"""Get current DateTime in UTC"""

207

208

@classmethod

209

def today(cls) -> DateTime:

210

"""Get today at start of day in local timezone"""

211

212

@classmethod

213

def instance(cls, dt, tz: str | Timezone | None = None) -> DateTime:

214

"""Create from standard datetime object"""

215

216

@classmethod

217

def fromtimestamp(cls, timestamp: float, tz: str | Timezone | None = None) -> DateTime:

218

"""Create from timestamp"""

219

220

@classmethod

221

def utcfromtimestamp(cls, timestamp: float) -> DateTime:

222

"""Create from timestamp in UTC"""

223

224

@classmethod

225

def fromordinal(cls, ordinal: int) -> DateTime:

226

"""Create from ordinal day number"""

227

228

@classmethod

229

def combine(cls, date, time, tzinfo=None) -> DateTime:

230

"""Combine date and time objects"""

231

232

@classmethod

233

def strptime(cls, date_string: str, format: str) -> DateTime:

234

"""Parse string with format (like datetime.strptime)"""

235

```

236

237

### Instance Manipulation

238

239

Methods for modifying DateTime instances.

240

241

```python { .api }

242

class DateTime:

243

def set(

244

self,

245

year: int | None = None,

246

month: int | None = None,

247

day: int | None = None,

248

hour: int | None = None,

249

minute: int | None = None,

250

second: int | None = None,

251

microsecond: int | None = None,

252

tz: str | Timezone | None = None

253

) -> DateTime:

254

"""

255

Set specific components, returning new DateTime.

256

257

Returns:

258

DateTime: New DateTime with specified components

259

"""

260

261

def on(self, year: int, month: int, day: int) -> DateTime:

262

"""

263

Set date components.

264

265

Returns:

266

DateTime: New DateTime with specified date

267

"""

268

269

def at(

270

self,

271

hour: int,

272

minute: int = 0,

273

second: int = 0,

274

microsecond: int = 0

275

) -> DateTime:

276

"""

277

Set time components.

278

279

Returns:

280

DateTime: New DateTime with specified time

281

"""

282

283

def replace(self, **kwargs) -> DateTime:

284

"""

285

Replace components (like standard datetime.replace).

286

287

Returns:

288

DateTime: New DateTime with replaced components

289

"""

290

291

def naive(self) -> DateTime:

292

"""

293

Remove timezone information.

294

295

Returns:

296

DateTime: Naive DateTime

297

"""

298

299

def in_timezone(self, tz: str | Timezone) -> DateTime:

300

"""

301

Convert to different timezone.

302

303

Parameters:

304

- tz: Target timezone

305

306

Returns:

307

DateTime: DateTime in target timezone

308

"""

309

310

def in_tz(self, tz: str | Timezone) -> DateTime:

311

"""Alias for in_timezone()"""

312

```

313

314

### Date and Time Arithmetic

315

316

Methods for adding and subtracting time periods.

317

318

```python { .api }

319

class DateTime:

320

def add(

321

self,

322

years: int = 0,

323

months: int = 0,

324

weeks: int = 0,

325

days: int = 0,

326

hours: int = 0,

327

minutes: int = 0,

328

seconds: float = 0,

329

microseconds: int = 0

330

) -> DateTime:

331

"""

332

Add time period to DateTime.

333

334

Returns:

335

DateTime: New DateTime with added period

336

"""

337

338

def subtract(

339

self,

340

years: int = 0,

341

months: int = 0,

342

weeks: int = 0,

343

days: int = 0,

344

hours: int = 0,

345

minutes: int = 0,

346

seconds: float = 0,

347

microseconds: int = 0

348

) -> DateTime:

349

"""

350

Subtract time period from DateTime.

351

352

Returns:

353

DateTime: New DateTime with subtracted period

354

"""

355

```

356

357

### Time Period Navigation

358

359

Methods for moving to specific time periods or boundaries.

360

361

```python { .api }

362

class DateTime:

363

def start_of(self, unit: str) -> DateTime:

364

"""

365

Move to start of time unit.

366

367

Parameters:

368

- unit: 'second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'century'

369

370

Returns:

371

DateTime: DateTime at start of specified unit

372

"""

373

374

def end_of(self, unit: str) -> DateTime:

375

"""

376

Move to end of time unit.

377

378

Parameters:

379

- unit: 'second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'century'

380

381

Returns:

382

DateTime: DateTime at end of specified unit

383

"""

384

385

def next(self, day_of_week: WeekDay | None = None, keep_time: bool = False) -> DateTime:

386

"""

387

Get next occurrence of weekday.

388

389

Parameters:

390

- day_of_week: Target weekday (None for next day)

391

- keep_time: Whether to preserve time components

392

393

Returns:

394

DateTime: Next occurrence

395

"""

396

397

def previous(self, day_of_week: WeekDay | None = None, keep_time: bool = False) -> DateTime:

398

"""

399

Get previous occurrence of weekday.

400

401

Parameters:

402

- day_of_week: Target weekday (None for previous day)

403

- keep_time: Whether to preserve time components

404

405

Returns:

406

DateTime: Previous occurrence

407

"""

408

409

def first_of(self, unit: str, day_of_week: WeekDay | None = None) -> DateTime:

410

"""

411

Get first occurrence in time unit.

412

413

Parameters:

414

- unit: 'month', 'quarter', 'year'

415

- day_of_week: Specific weekday (None for first day)

416

417

Returns:

418

DateTime: First occurrence in unit

419

"""

420

421

def last_of(self, unit: str, day_of_week: WeekDay | None = None) -> DateTime:

422

"""

423

Get last occurrence in time unit.

424

425

Parameters:

426

- unit: 'month', 'quarter', 'year'

427

- day_of_week: Specific weekday (None for last day)

428

429

Returns:

430

DateTime: Last occurrence in unit

431

"""

432

433

def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> DateTime:

434

"""

435

Get nth occurrence of weekday in time unit.

436

437

Parameters:

438

- unit: 'month', 'quarter', 'year'

439

- nth: Occurrence number (1-5, -1 for last)

440

- day_of_week: Target weekday

441

442

Returns:

443

DateTime: Nth occurrence

444

"""

445

446

def average(self, dt: DateTime | None = None) -> DateTime:

447

"""

448

Get average DateTime between this and another.

449

450

Parameters:

451

- dt: Other DateTime (defaults to now)

452

453

Returns:

454

DateTime: Average DateTime

455

"""

456

```

457

458

### Comparisons and Tests

459

460

Methods for comparing DateTimes and testing properties.

461

462

```python { .api }

463

class DateTime:

464

def is_local(self) -> bool:

465

"""Check if timezone is local system timezone"""

466

467

def is_utc(self) -> bool:

468

"""Check if timezone is UTC"""

469

470

def is_dst(self) -> bool:

471

"""Check if daylight saving time is active"""

472

473

def is_future(self) -> bool:

474

"""Check if DateTime is in the future"""

475

476

def is_past(self) -> bool:

477

"""Check if DateTime is in the past"""

478

479

def is_leap_year(self) -> bool:

480

"""Check if year is a leap year"""

481

482

def is_long_year(self) -> bool:

483

"""Check if ISO year has 53 weeks"""

484

485

def is_same_day(self, dt: DateTime) -> bool:

486

"""Check if same calendar day as another DateTime"""

487

488

def is_anniversary(self, dt: DateTime | None = None) -> bool:

489

"""Check if anniversary date (same month/day)"""

490

491

def closest(self, *dts: DateTime) -> DateTime:

492

"""

493

Get closest DateTime from list.

494

495

Parameters:

496

- *dts: DateTime objects to compare

497

498

Returns:

499

DateTime: Closest DateTime

500

"""

501

502

def farthest(self, *dts: DateTime) -> DateTime:

503

"""

504

Get farthest DateTime from list.

505

506

Parameters:

507

- *dts: DateTime objects to compare

508

509

Returns:

510

DateTime: Farthest DateTime

511

"""

512

```

513

514

### Differences and Formatting

515

516

Methods for calculating differences and formatting output.

517

518

```python { .api }

519

class DateTime:

520

def diff(self, dt: DateTime | None = None, abs: bool = True) -> Interval:

521

"""

522

Calculate difference as Interval.

523

524

Parameters:

525

- dt: Other DateTime (defaults to now)

526

- abs: Whether to return absolute difference

527

528

Returns:

529

Interval: Time difference

530

"""

531

532

def diff_for_humans(

533

self,

534

other: DateTime | None = None,

535

absolute: bool = False,

536

locale: str | None = None

537

) -> str:

538

"""

539

Get human-readable difference description.

540

541

Parameters:

542

- other: Other DateTime (defaults to now)

543

- absolute: Whether to omit ago/from now

544

- locale: Locale for formatting

545

546

Returns:

547

str: Human-readable difference (e.g., "2 hours ago")

548

"""

549

```

550

551

### Properties

552

553

Key properties available on DateTime instances.

554

555

```python { .api }

556

class DateTime:

557

@property

558

def float_timestamp(self) -> float:

559

"""Unix timestamp as float"""

560

561

@property

562

def int_timestamp(self) -> int:

563

"""Unix timestamp as integer"""

564

565

@property

566

def offset(self) -> int:

567

"""UTC offset in seconds"""

568

569

@property

570

def offset_hours(self) -> float:

571

"""UTC offset in hours"""

572

573

@property

574

def timezone(self) -> Timezone | FixedTimezone:

575

"""Timezone object"""

576

577

@property

578

def tz(self) -> Timezone | FixedTimezone:

579

"""Alias for timezone"""

580

581

@property

582

def timezone_name(self) -> str:

583

"""Timezone name string"""

584

585

@property

586

def age(self) -> int:

587

"""Age in years from now"""

588

```

589

590

## Usage Examples

591

592

### Creating DateTimes

593

594

```python

595

import pendulum

596

597

# Current time

598

now = pendulum.now()

599

paris_now = pendulum.now('Europe/Paris')

600

601

# Specific datetime

602

dt = pendulum.datetime(2024, 3, 15, 14, 30, 0)

603

local_dt = pendulum.local(2024, 3, 15, 14, 30, 0)

604

605

# From string

606

parsed = pendulum.parse('2024-03-15T14:30:00Z')

607

formatted = pendulum.from_format('15/03/2024 14:30', 'DD/MM/YYYY HH:mm')

608

609

# From timestamp

610

from_ts = pendulum.from_timestamp(1710505800)

611

```

612

613

### DateTime Manipulation

614

615

```python

616

dt = pendulum.now()

617

618

# Modify components

619

new_dt = dt.set(hour=15, minute=30)

620

date_changed = dt.on(2024, 12, 25)

621

time_changed = dt.at(9, 0, 0)

622

623

# Timezone conversion

624

utc_dt = dt.in_timezone('UTC')

625

tokyo_dt = dt.in_timezone('Asia/Tokyo')

626

627

# Arithmetic

628

future = dt.add(days=7, hours=3)

629

past = dt.subtract(months=2, days=5)

630

631

# Period navigation

632

start_of_month = dt.start_of('month')

633

end_of_year = dt.end_of('year')

634

next_monday = dt.next(pendulum.MONDAY)

635

```

636

637

### Comparisons and Tests

638

639

```python

640

dt1 = pendulum.now()

641

dt2 = pendulum.now('Europe/Paris')

642

643

# Standard comparisons work

644

if dt1 > dt2:

645

print("Later")

646

647

# Pendulum-specific tests

648

if dt1.is_future():

649

print("In the future")

650

651

if dt1.is_same_day(dt2):

652

print("Same day")

653

654

# Find closest/farthest

655

closest = dt1.closest(dt2, pendulum.tomorrow())

656

```

657

658

## String Formatting

659

660

DateTime provides various string formatting methods for different standards and use cases.

661

662

```python { .api }

663

class DateTime:

664

def to_time_string(self) -> str:

665

"""Format as time string (HH:mm:ss)"""

666

667

def to_datetime_string(self) -> str:

668

"""Format as datetime string (YYYY-MM-DD HH:mm:ss)"""

669

670

def to_day_datetime_string(self) -> str:

671

"""Format as day, date and time string"""

672

673

def to_atom_string(self) -> str:

674

"""Format as ATOM string"""

675

676

def to_cookie_string(self) -> str:

677

"""Format as COOKIE string"""

678

679

def to_iso8601_string(self) -> str:

680

"""Format as ISO 8601 string"""

681

682

def to_rfc822_string(self) -> str:

683

"""Format as RFC 822 string"""

684

685

def to_rfc850_string(self) -> str:

686

"""Format as RFC 850 string"""

687

688

def to_rfc1036_string(self) -> str:

689

"""Format as RFC 1036 string"""

690

691

def to_rfc1123_string(self) -> str:

692

"""Format as RFC 1123 string"""

693

694

def to_rfc2822_string(self) -> str:

695

"""Format as RFC 2822 string"""

696

697

def to_rfc3339_string(self) -> str:

698

"""Format as RFC 3339 string"""

699

700

def to_rss_string(self) -> str:

701

"""Format as RSS string"""

702

703

def to_w3c_string(self) -> str:

704

"""Format as W3C string"""

705

706

def format(self, fmt: str, locale: str | None = None) -> str:

707

"""Format using custom format string"""

708

709

def for_json(self) -> str:

710

"""JSON serialization (ISO format)"""

711

```

712

713

## Additional Properties

714

715

Properties inherited from Date class and specific to DateTime.

716

717

```python { .api }

718

class DateTime:

719

@property

720

def day_of_week(self) -> WeekDay:

721

"""Day of the week (MONDAY=0 through SUNDAY=6)"""

722

723

@property

724

def day_of_year(self) -> int:

725

"""Day of the year (1-366)"""

726

727

@property

728

def week_of_year(self) -> int:

729

"""ISO week number of the year"""

730

731

@property

732

def days_in_month(self) -> int:

733

"""Number of days in the current month"""

734

735

@property

736

def week_of_month(self) -> int:

737

"""Week number within the month"""

738

739

@property

740

def quarter(self) -> int:

741

"""Quarter of the year (1-4)"""

742

```

743

744

## Utility Methods

745

746

Additional utility methods for component extraction and compatibility.

747

748

```python { .api }

749

class DateTime:

750

def date(self) -> Date:

751

"""Extract date component as Date object"""

752

753

def time(self) -> Time:

754

"""Extract time component as Time object"""

755

756

def get_offset(self) -> int | None:

757

"""Get UTC offset in seconds"""

758

759

def astimezone(self, tz: datetime.tzinfo | None = None) -> DateTime:

760

"""Convert to timezone (datetime compatibility)"""

761

762

def is_birthday(self, dt: datetime.datetime | None = None) -> bool:

763

"""Alias for is_anniversary() - check if birthday/anniversary"""

764

```

765

766

## Class Constants

767

768

```python { .api }

769

class DateTime:

770

EPOCH: ClassVar[DateTime] # DateTime(1970, 1, 1, tzinfo=UTC)

771

min: ClassVar[DateTime] # DateTime(1, 1, 1, 0, 0, tzinfo=UTC)

772

max: ClassVar[DateTime] # DateTime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=UTC)

773

```