Write a python function that produces list of months in YYYYMM given two YYYYMM values |
submit Problem Solving Skills, Human vs AI
Published Mar 04 '25 |
Tried #DeepSeek and #ChatGPT to write Python code given the prompt given two integers in format of YYYYMM, produce python code that produce all months in between them in YYYYMM format. For example, given 202404 and 202411, produce a list of months between them.
Here’s a Python function that takes two integers in the format YYYYMM
and generates a list of all months in between them, inclusive:
```python from datetime import datetime, timedelta
def generate_months_between(start_ym, end_ym): # Convert the input integers to strings start_str = str(start_ym) end_str = str(end_ym)
# Parse the strings into datetime objects
start_date = datetime.strptime(start_str, "%Y%m")
end_date = datetime.strptime(end_str, "%Y%m")
# Initialize the list to store the months
months = []
# Iterate from the start date to the end date
current_date = start_date
while current_date <= end_date:
# Append the current month in YYYYMM format
months.append(current_date.strftime("%Y%m"))
# Move to the next month
if current_date.month == 12:
current_date = current_date.replace(year=current_date.year + 1, month=1)
else:
current_date = current_date.replace(month=current_date.month + 1)
return months
start_ym = 202404 end_ym = 202411 result = generate_months_between(start_ym, end_ym) print(result) ```
python
['202404', '202405', '202406', '202407', '202408', '202409', '202410', '202411']
YYYYMM
) into strings and then parses them into datetime
objects using strptime
.YYYYMM
string format and added to the list.This code handles edge cases like transitioning from December to January and works for any valid range of months.
Here's a Python function to generate all months between two given integers in YYYYMM
format:
```python from datetime import datetime, timedelta
def generate_months(start_yyyymm, end_yyyymm): start_date = datetime.strptime(str(start_yyyymm), "%Y%m") end_date = datetime.strptime(str(end_yyyymm), "%Y%m")
months = []
while start_date <= end_date:
months.append(start_date.strftime("%Y%m"))
start_date = (start_date.replace(day=1) + timedelta(days=32)).replace(day=1)
return months
print(generate_months(202404, 202411)) ```
datetime
objects.YYYYMM
format.end_yyyymm
.python
['202404', '202405', '202406', '202407', '202408', '202409', '202410', '202411']
Let me know if you need modifications! ?
Terms of Use: You are in agreement with our Terms of Services and Privacy Policy. If you have any question or concern to any information published on SaveNowClub, please feel free to write to us at savenowclub@gmail.com