Here is an example code in Python to create a dynamic array of 12 months based on the present month:
import datetime
# Get the current month and year
now = datetime.datetime.now()
current_month = now.month
current_year = now.year
# Initialize the array with empty strings
months = [""] * 12
# Fill in the array with the names of the months
for i in range(12):
month = (current_month + i) % 12
year_offset = (current_month + i - 1) // 12
year = current_year + year_offset
months[i] = datetime.date(year, month, 1).strftime("%B")
# Print the array for testing
print(months)
Explanation:
datetime
module to work with dates.now()
function to get the current date and time.month
and year
attributes.datetime
object for each month using the date()
function.strftime()
function to format the month name as a string.This code will generate an array of 12 months starting from the current month and ending with the month which is 11 months ahead of the current month.
Asked: 2023-01-31 11:00:00 +0000
Seen: 7 times
Last updated: Apr 01 '23