Skip to content

Instantly share code, notes, and snippets.

@ZenithClown
Last active October 31, 2023 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZenithClown/d2dd294c5f528459e16b139c04c0b182 to your computer and use it in GitHub Desktop.
Save ZenithClown/d2dd294c5f528459e16b139c04c0b182 to your computer and use it in GitHub Desktop.
An Extension of datetime Module to Provide additional Functionalities

Date-Time Utility Functions

a set of utility functions extended from datetime module

Colab Notebook

# -*- 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)
@nxlogics
Copy link

nxlogics commented Apr 13, 2023

Hi there, the following changes are required:

  • timedelta can be provided on other levels (like hours, minutes, etc.),
  • Provide detail documentation about functionalities and usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment