Skip to content

Instantly share code, notes, and snippets.

@omarfsosa
Created January 26, 2021 18:02
Show Gist options
  • Save omarfsosa/2df8968fa57b4b16d161349c75526b4b to your computer and use it in GitHub Desktop.
Save omarfsosa/2df8968fa57b4b16d161349c75526b4b to your computer and use it in GitHub Desktop.
Extend a pandas datetime index
import pandas as pd
def extend_datetime_index(index: pd.DatetimeIndex, end: pd.Timestamp = None, periods: int = None) -> pd.DatetimeIndex:
"""
Minimal function for extending a pandas DateTimeIndex.
Original attributes of the `index` (e.g name or tz) are not kept.
Only the `freq` attribute is preserved.
"""
if (bool(end) == bool(periods)): # xor
msg = "Of the 2 parameters, `end` and `periods`, exactly 1 must be specified."
raise ValueError(msg)
freq = index.freq
start = index[0]
if end:
extended = pd.date_range(
start,
end=end,
freq=freq,
)
elif periods:
extended = pd.date_range(
start,
periods=periods + len(index),
freq=freq,
)
return extended
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment