-3

Lets say I have a starting date of 12/30/2019 (monday) and an ending date of 1/5/2020 (sunday). I want to assign 7 variables for each day from the starting to ending date, inclusive. The starting and ending dates will be the only given values, the other 5 dates will be derived by the script.

the variables I will assign will be:

monday = '12 30 2019'
sunday = '1 5 2020'

given the assigned values for monday and sunday, the five days in between will be assigned dynamically as such:

tuesday = '12 31 2019'
wednesday = '1 1 2020'
thursday = '1 2 2020'
friday = '1 3 2020'
saturday = '1 4 2020'

This code should work for any given starting and ending date, in which the starting date will always be a monday with ending date always being the next sunday after. I've tried and failed using the datetime module.

jbenfleming
  • 85
  • 3
  • 11

1 Answers1

1

You can do it with datetime module:

import datetime

monday = '12 30 2019'
sunday = '1 5 2020'

def next_day(day):
    day_dt = datetime.datetime.strptime(day, '%m %d %Y')
    next_day_dt = day_dt + datetime.timedelta(days = 1)
    next_day = next_day_dt.strftime('%#m %#d %Y')
    return next_day

tuesday = next_day(monday)
print(f'tuesday = {tuesday}')
wednesday = next_day(tuesday)
print(f'tuesday = {tuesday}')
thursday = next_day(wednesday)
print(f'thursday = {thursday}')
friday = next_day(thursday)
print(f'friday = {friday}')
saturday = next_day(friday)
print(f'saturday = {saturday}')

Or,

def next_day(day):
    day_dt = datetime.datetime.strptime(day, '%m %d %Y')
    next_day_dt = day_dt + datetime.timedelta(days = 1)
    next_day = next_day_dt.strftime('%#m %#d %Y')
    return next_day

monday = '12 30 2019'
sunday = '1 5 2020'

date = {}
date['monday'] = monday
date['sunday'] = sunday

week = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']

for prev_day, day in zip(week, week[1:]):
    if day == 'sunday': break
    date[day] = next_day(date[prev_day])

for day,dt in date.items():
    if day in ['monday', 'sunday']: continue
    print(f"{day} = '{dt}'")

Output:

tuesday = '12 31 2019'
wednesday = '1 1 2020'
thursday = '1 2 2020'
friday = '1 3 2020'
saturday = '1 4 2020'

NOTE: Even though you can name variable dynamically, in Python it is often a bad idea. Using a dictionary instead, is the best practice.

Reference:

  1. How can you dynamically create variables via a while loop?

  2. How do I create a variable number of variables?

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52