Last active
October 31, 2023 08:52
-
-
Save ZenithClown/d2dd294c5f528459e16b139c04c0b182 to your computer and use it in GitHub Desktop.
An Extension of datetime Module to Provide additional Functionalities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
""" | |
A list of utility functions related to datetime objects. The module | |
uses the core `datetime` module to manipulate "date-time" object, and | |
thus the file is named as `datetime_` to let the enduser know its | |
capabilities. | |
""" | |
import datetime as dt | |
def date_range(start : dt.date, end : dt.date) -> dt.date: | |
""" | |
Create an Iterable Object of Dates b/w Start and End | |
Given a start date and an end date, the function creates an | |
iterable of all the dates. Simply, the function can be used as an | |
iterator like: | |
```python | |
import datetime as dt | |
import datetime_ as dt_ | |
iter = dt_.date_range(start = dt.date(2023, 1, 1), end = dt.date(2023, 1, 31)) | |
print(next(iter)) # prints the date | |
``` | |
For more robust and one line approach, all dates can be fetched | |
by: | |
```python | |
import datetime as dt | |
import datetime_ as dt_ | |
iter = dt_.date_range(start = dt.date(2023, 1, 1), end = dt.date(2023, 1, 31)) | |
all_dates = list(iter) | |
``` | |
The `pandas` module provides `pd.Timestamp` which is a wrapper of | |
the python `datetime` module. To simply convert any `datetime` | |
object to a `pd.Timestamp` use the `map` method like: | |
```python | |
import pandas as pd | |
timestamps = list(map(lambda x : pd.Timestamp(str(x)), all_dates)) | |
``` | |
Thus, the function is an additional wrapper over the `datetime` | |
functions available on python. | |
! The function only works with an `dt.date` object. | |
TODO `datetime_range()` for more functionalities. | |
""" | |
span = end - start # dt object can be subtracted easily | |
for i in range(span.days + 1): | |
yield start + dt.timedelta(days = i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi there, the following changes are required:
timedelta
can be provided on other levels (like hours, minutes, etc.),