-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
datetime_range.py
333 lines (286 loc) · 9.82 KB
/
datetime_range.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from __future__ import annotations
import contextlib
from typing import TYPE_CHECKING, overload
from polars import functions as F
from polars._utils.deprecation import deprecate_saturating
from polars._utils.parse_expr_input import parse_as_expression
from polars._utils.wrap import wrap_expr
from polars.functions.range._utils import parse_interval_argument
with contextlib.suppress(ImportError): # Module not available when building docs
import polars.polars as plr
if TYPE_CHECKING:
from datetime import date, datetime, timedelta
from typing import Literal
from polars import Expr, Series
from polars.type_aliases import ClosedInterval, IntoExprColumn, TimeUnit
@overload
def datetime_range(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: Literal[False] = ...,
) -> Expr: ...
@overload
def datetime_range(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: Literal[True],
) -> Series: ...
@overload
def datetime_range(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: bool,
) -> Series | Expr: ...
def datetime_range(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = "1d",
*,
closed: ClosedInterval = "both",
time_unit: TimeUnit | None = None,
time_zone: str | None = None,
eager: bool = False,
) -> Series | Expr:
"""
Generate a datetime range.
Parameters
----------
start
Lower bound of the datetime range.
end
Upper bound of the datetime range.
interval
Interval of the range periods, specified as a Python `timedelta` object
or using the Polars duration string language (see "Notes" section below).
closed : {'both', 'left', 'right', 'none'}
Define which sides of the range are closed (inclusive).
time_unit : {None, 'ns', 'us', 'ms'}
Time unit of the resulting `Datetime` data type.
time_zone
Time zone of the resulting `Datetime` data type.
eager
Evaluate immediately and return a `Series`.
If set to `False` (default), return an expression instead.
Returns
-------
Expr or Series
Column of data type :class:`Datetime`.
Notes
-----
`interval` is created according to the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
Or combine them:
"3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day (which may
not be 24 hours, due to daylight savings). Similarly for "calendar week",
"calendar month", "calendar quarter", and "calendar year".
Examples
--------
Using Polars duration string to specify the interval:
>>> from datetime import datetime
>>> pl.datetime_range(
... datetime(2022, 1, 1), datetime(2022, 3, 1), "1mo", eager=True
... ).alias("datetime")
shape: (3,)
Series: 'datetime' [datetime[μs]]
[
2022-01-01 00:00:00
2022-02-01 00:00:00
2022-03-01 00:00:00
]
Using `timedelta` object to specify the interval:
>>> from datetime import date, timedelta
>>> pl.datetime_range(
... date(1985, 1, 1),
... date(1985, 1, 10),
... timedelta(days=1, hours=12),
... time_unit="ms",
... eager=True,
... ).alias("datetime")
shape: (7,)
Series: 'datetime' [datetime[ms]]
[
1985-01-01 00:00:00
1985-01-02 12:00:00
1985-01-04 00:00:00
1985-01-05 12:00:00
1985-01-07 00:00:00
1985-01-08 12:00:00
1985-01-10 00:00:00
]
Specifying a time zone:
>>> pl.datetime_range(
... datetime(2022, 1, 1),
... datetime(2022, 3, 1),
... "1mo",
... time_zone="America/New_York",
... eager=True,
... ).alias("datetime")
shape: (3,)
Series: 'datetime' [datetime[μs, America/New_York]]
[
2022-01-01 00:00:00 EST
2022-02-01 00:00:00 EST
2022-03-01 00:00:00 EST
]
"""
interval = deprecate_saturating(interval)
interval = parse_interval_argument(interval)
if time_unit is None and "ns" in interval:
time_unit = "ns"
start_pyexpr = parse_as_expression(start)
end_pyexpr = parse_as_expression(end)
result = wrap_expr(
plr.datetime_range(
start_pyexpr, end_pyexpr, interval, closed, time_unit, time_zone
)
)
if eager:
return F.select(result).to_series()
return result
@overload
def datetime_ranges(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: Literal[False] = ...,
) -> Expr: ...
@overload
def datetime_ranges(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: Literal[True],
) -> Series: ...
@overload
def datetime_ranges(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = ...,
*,
closed: ClosedInterval = ...,
time_unit: TimeUnit | None = ...,
time_zone: str | None = ...,
eager: bool,
) -> Series | Expr: ...
def datetime_ranges(
start: datetime | date | IntoExprColumn,
end: datetime | date | IntoExprColumn,
interval: str | timedelta = "1d",
*,
closed: ClosedInterval = "both",
time_unit: TimeUnit | None = None,
time_zone: str | None = None,
eager: bool = False,
) -> Series | Expr:
"""
Create a column of datetime ranges.
Parameters
----------
start
Lower bound of the datetime range.
end
Upper bound of the datetime range.
interval
Interval of the range periods, specified as a Python `timedelta` object
or using the Polars duration string language (see "Notes" section below).
closed : {'both', 'left', 'right', 'none'}
Define which sides of the range are closed (inclusive).
time_unit : {None, 'ns', 'us', 'ms'}
Time unit of the resulting `Datetime` data type.
time_zone
Time zone of the resulting `Datetime` data type.
eager
Evaluate immediately and return a `Series`.
If set to `False` (default), return an expression instead.
Notes
-----
`interval` is created according to the following string language:
- 1ns (1 nanosecond)
- 1us (1 microsecond)
- 1ms (1 millisecond)
- 1s (1 second)
- 1m (1 minute)
- 1h (1 hour)
- 1d (1 calendar day)
- 1w (1 calendar week)
- 1mo (1 calendar month)
- 1q (1 calendar quarter)
- 1y (1 calendar year)
Or combine them:
"3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds
By "calendar day", we mean the corresponding time on the next day (which may
not be 24 hours, due to daylight savings). Similarly for "calendar week",
"calendar month", "calendar quarter", and "calendar year".
Returns
-------
Expr or Series
Column of data type `List(Datetime)`.
Examples
--------
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "start": [datetime(2022, 1, 1), datetime(2022, 1, 2)],
... "end": datetime(2022, 1, 3),
... }
... )
>>> with pl.Config(fmt_str_lengths=100):
... df.select(datetime_range=pl.datetime_ranges("start", "end"))
shape: (2, 1)
┌─────────────────────────────────────────────────────────────────┐
│ datetime_range │
│ --- │
│ list[datetime[μs]] │
╞═════════════════════════════════════════════════════════════════╡
│ [2022-01-01 00:00:00, 2022-01-02 00:00:00, 2022-01-03 00:00:00] │
│ [2022-01-02 00:00:00, 2022-01-03 00:00:00] │
└─────────────────────────────────────────────────────────────────┘
"""
interval = deprecate_saturating(interval)
interval = parse_interval_argument(interval)
if time_unit is None and "ns" in interval:
time_unit = "ns"
start_pyexpr = parse_as_expression(start)
end_pyexpr = parse_as_expression(end)
result = wrap_expr(
plr.datetime_ranges(
start_pyexpr, end_pyexpr, interval, closed, time_unit, time_zone
)
)
if eager:
return F.select(result).to_series()
return result