0
# Time & Date Utilities
1
2
Time zone handling, datetime parsing, relative time formatting, and date range generation. Supports ISO 8601 parsing, human-readable time deltas, timezone-aware operations, and comprehensive date manipulation utilities.
3
4
## Capabilities
5
6
### Timezone Support
7
8
Comprehensive timezone implementations with DST support.
9
10
```python { .api }
11
class ConstantTZInfo(tzinfo):
12
"""Timezone info for fixed UTC offsets."""
13
def __init__(self, name=None, offset=None): ...
14
def utcoffset(self, dt): ...
15
def tzname(self, dt): ...
16
def dst(self, dt): ...
17
18
class LocalTZInfo(tzinfo):
19
"""Timezone info for local timezone with DST support."""
20
def utcoffset(self, dt): ...
21
def tzname(self, dt): ...
22
def dst(self, dt): ...
23
24
class USTimeZone(tzinfo):
25
"""US timezone implementation with historical DST rules."""
26
def __init__(self, name, offset, dst_name, dst_offset, dst_start, dst_end): ...
27
def utcoffset(self, dt): ...
28
def tzname(self, dt): ...
29
def dst(self, dt): ...
30
```
31
32
### DateTime Parsing and Conversion
33
34
Parse and convert datetime objects with timezone support.
35
36
```python { .api }
37
def dt_to_timestamp(dt):
38
"""
39
Convert datetime to Unix timestamp.
40
41
Parameters:
42
- dt (datetime): Datetime object to convert
43
44
Returns:
45
float: Unix timestamp
46
"""
47
48
def isoparse(iso_str):
49
"""
50
Parse ISO 8601 datetime strings.
51
52
Parameters:
53
- iso_str (str): ISO 8601 formatted datetime string
54
55
Returns:
56
datetime: Parsed datetime object with timezone info
57
"""
58
59
def strpdate(string, format):
60
"""
61
Parse date string with timezone awareness.
62
63
Parameters:
64
- string (str): Date string to parse
65
- format (str): strptime format string
66
67
Returns:
68
datetime: Parsed datetime object
69
"""
70
```
71
72
### Time Delta Processing
73
74
Parse and format time intervals and durations.
75
76
```python { .api }
77
def parse_timedelta(text):
78
"""
79
Parse human-readable timedelta strings.
80
81
Parameters:
82
- text (str): Human-readable time duration (e.g., '1h 30m', '2 days')
83
84
Returns:
85
timedelta: Parsed time duration
86
"""
87
```
88
89
### Relative Time Formatting
90
91
Format time differences in human-readable formats.
92
93
```python { .api }
94
def decimal_relative_time(d, other=None, **kwargs):
95
"""
96
Decimal relative time description.
97
98
Parameters:
99
- d (datetime): Target datetime
100
- other (datetime, optional): Reference datetime (default: now)
101
102
Returns:
103
str: Decimal relative time string
104
"""
105
106
def relative_time(d, other=None, ndigits=0):
107
"""
108
Human-readable relative time.
109
110
Parameters:
111
- d (datetime): Target datetime
112
- other (datetime, optional): Reference datetime (default: now)
113
- ndigits (int): Number of decimal places for precision
114
115
Returns:
116
str: Human-readable relative time (e.g., '2 hours ago', 'in 3 days')
117
"""
118
```
119
120
### Date Range Generation
121
122
Generate sequences of dates for iteration and analysis.
123
124
```python { .api }
125
def daterange(start, stop, step=1, inclusive=False):
126
"""
127
Generate date ranges.
128
129
Parameters:
130
- start (date): Start date
131
- stop (date): End date
132
- step (int): Step size in days
133
- inclusive (bool): Include end date
134
135
Yields:
136
date: Each date in the range
137
"""
138
```
139
140
## Usage Examples
141
142
```python
143
from boltons.timeutils import (
144
isoparse, relative_time, parse_timedelta, daterange,
145
dt_to_timestamp, LocalTZInfo, UTC
146
)
147
from datetime import datetime, date, timedelta
148
149
# Parse ISO 8601 strings
150
iso_string = "2023-12-25T15:30:00Z"
151
dt = isoparse(iso_string)
152
print(dt) # 2023-12-25 15:30:00+00:00
153
154
# Convert to timestamp
155
timestamp = dt_to_timestamp(dt)
156
print(timestamp) # Unix timestamp
157
158
# Human-readable relative time
159
now = datetime.now(UTC)
160
past = now - timedelta(hours=2, minutes=30)
161
relative = relative_time(past, now)
162
print(relative) # "2 hours ago"
163
164
future = now + timedelta(days=3)
165
relative_future = relative_time(future, now)
166
print(relative_future) # "in 3 days"
167
168
# Parse time durations
169
duration_str = "1h 30m 45s"
170
duration = parse_timedelta(duration_str)
171
print(duration) # timedelta(hours=1, minutes=30, seconds=45)
172
173
# Generate date ranges
174
start_date = date(2023, 1, 1)
175
end_date = date(2023, 1, 7)
176
for day in daterange(start_date, end_date):
177
print(day) # 2023-01-01, 2023-01-02, ..., 2023-01-06
178
179
# Timezone-aware operations
180
local_tz = LocalTZInfo()
181
local_time = datetime.now(local_tz)
182
utc_time = local_time.astimezone(UTC)
183
print(f"Local: {local_time}")
184
print(f"UTC: {utc_time}")
185
```
186
187
### Advanced Time Operations
188
189
```python
190
from boltons.timeutils import USTimeZone, ConstantTZInfo
191
from datetime import datetime
192
193
# US timezone with DST
194
eastern = USTimeZone(
195
'EST', timedelta(hours=-5),
196
'EDT', timedelta(hours=-4),
197
dst_start=(3, 2, 0), # Second Sunday in March
198
dst_end=(11, 1, 0) # First Sunday in November
199
)
200
201
# Create timezone-aware datetime
202
dt_eastern = datetime(2023, 7, 4, 12, 0, 0, tzinfo=eastern)
203
print(dt_eastern) # 2023-07-04 12:00:00-04:00 (EDT in summer)
204
205
# Fixed offset timezone
206
pst = ConstantTZInfo('PST', timedelta(hours=-8))
207
dt_pst = datetime(2023, 12, 25, 10, 0, 0, tzinfo=pst)
208
print(dt_pst) # 2023-12-25 10:00:00-08:00
209
210
# Complex relative time formatting
211
start = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
212
end = datetime(2023, 1, 15, 18, 30, 45, tzinfo=UTC)
213
214
relative_precise = relative_time(end, start, ndigits=2)
215
print(relative_precise) # Precise relative time with decimals
216
```
217
218
## Types
219
220
```python { .api }
221
# Timezone constants
222
ZERO = timedelta(0) # Zero timedelta constant
223
HOUR = timedelta(hours=1) # One hour timedelta constant
224
UTC = ConstantTZInfo('UTC', ZERO) # UTC timezone instance
225
226
# Epoch reference
227
EPOCH_AWARE = datetime(1970, 1, 1, tzinfo=UTC) # Timezone-aware Unix epoch
228
```