Search code examples
pythoncalendar

How to check what month it is? Python


I am writing a code which assigns certain data to different seasons. What I want is for the program to print the various data depending on what month it currently is.

Autumn = 'September'
Autumn = 'October'
Autumn = 'November'
Autumn = 'December'
Autumn = 'January' #(The start Jan 01)
Spring = 'January' #(Jan 02 onwards)
Spring = 'February'
Spring = 'March'
Spring = 'April' #(The start April 04)
Summer = 'April' #(April 05 onwards)
Summer = 'May'
Summer = 'June'
Summer = 'July'

Solution

  • You can use the strftime() function from the time module. This will store the current month in a variable called current_month.

    from time import strftime
    current_month = strftime('%B')
    

    If you want to get the current season from this, try this function:

    def get_season(month):
        seasons = {
        'Autumn': ['September', 'October', 'November', 'December', 'January'],
        'Spring': ['January', 'February', 'March', 'April'],
        'Summer': ['April', 'May', 'June', 'July']
        }
    
        for season in seasons:
            if month in seasons[season]:
                return season
        return 'Invalid input month'
    

    Currently, this will not solve the date conflicts that you specified, as any day in January will return 'Autumn', and any day in April will get you 'Spring'.