Created
November 16, 2023 20:37
-
-
Save aeveltstra/c5ac1567b78aecca11602fc9a9ffeb26 to your computer and use it in GitHub Desktop.
Python date and hour ranges for iterating
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
# These tests help understand how python generates ranges of dates | |
# and hours that can be iterated over. | |
import datetime | |
def make_date_by_day(days_back): | |
now = datetime.datetime.utcnow() | |
at_9am = datetime.datetime(now.year, now.month, now.day, 9, 0,0,0) | |
back_then = at_9am - datetime.timedelta(days=abs(days_back)) | |
return back_then | |
# Create a range of days | |
def create_a_range_of_days(): | |
print("Running test function 'create_a_range_of_days'...") | |
days_back = 7 | |
DATE_RANGE_STOP = 0 | |
DATE_RANGE_STEP = -1 | |
days = range(days_back, DATE_RANGE_STOP, DATE_RANGE_STEP) | |
for day in days: | |
start_date = make_date_by_day(day) | |
end_date = make_date_by_day(day - 1) | |
print(f"Day {day} from {start_date} to {end_date}") | |
def make_date_by_hour(hours_back): | |
now = datetime.datetime.utcnow() | |
at_whole_hour = datetime.datetime(now.year, now.month, now.day, now.hour, 0,0,0) | |
back_then = at_whole_hour - datetime.timedelta(hours=abs(hours_back)) | |
return back_then | |
# Create a range of hours | |
def create_a_range_of_hours(): | |
print("Running test function 'create_a_range_of_hours'...") | |
days_back = 2 | |
HOUR_RANGE_STOP = 0 | |
HOUR_RANGE_STEP = -1 | |
HOURS_PER_DAY = 24 | |
hours = range(days_back * HOURS_PER_DAY, HOUR_RANGE_STOP, HOUR_RANGE_STEP) | |
for hour in hours: | |
start_hour = make_date_by_hour(hour) | |
end_hour = make_date_by_hour(hour - 1) | |
print(f"Hour {hour} from {start_hour} to {end_hour}") | |
def main(): | |
print("Running tests...") | |
create_a_range_of_days() | |
create_a_range_of_hours() | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using Python 3.8. These functions are used live with one of my clients.