Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check what month it is? Python

I am writing a code which assigns certain data to different seasons. I wanted 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 = 'Apirl' #(April 05 onwards)
Summer = 'May'
Summer = 'June'
Summer = 'July'
like image 796
Hamzah Akhtar Avatar asked Apr 04 '14 22:04

Hamzah Akhtar


1 Answers

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': ['Apirl', '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'.

like image 91
Lily Mara Avatar answered Oct 05 '22 11:10

Lily Mara