Skip to content

Instantly share code, notes, and snippets.

@berlotto
Last active October 6, 2021 18:14
Show Gist options
  • Save berlotto/60ee08a203c3c03651fbf1f66a1cf1e0 to your computer and use it in GitHub Desktop.
Save berlotto/60ee08a203c3c03651fbf1f66a1cf1e0 to your computer and use it in GitHub Desktop.
Método para quebrar um range de datas em frequências definidas (mensal, quinzenal e semanal)

How to use

O método retorna uma lista de tuplas com as datas conforme frequencia definida.

quebra_periodo(start_date_p, end_date_p, freq='mensal')

quebra_periodo(start_date_p, end_date_p, freq='quinzenal')

quebra_periodo(start_date_p, end_date_p, freq='semanal')

Based on: https://stackoverflow.com/a/51294302/4902316

def quebra_periodo(begin:str, end:str, freq: str = 'mensal') -> List[Tuple]:
dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
#print(today)
tomorrow = today + one_day
if freq == 'mensal':
if tomorrow.month != today.month:
start_dates.append(tomorrow)
end_dates.append(today)
elif freq == 'quinzenal':
if tomorrow.month != today.month or tomorrow.day == 16:
start_dates.append(tomorrow)
end_dates.append(today)
elif freq == 'semanal':
week_today = int(today.strftime("%U")) # %U - weeknumber starting on SUNDAY
week_tomor = int(tomorrow.strftime("%U"))
if week_today != week_tomor:
start_dates.append(tomorrow)
end_dates.append(today)
today = tomorrow
end_dates.append(dt_end)
return list(zip(start_dates,end_dates))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment