How to check what month it is? Python

Question:

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'
Asked By: Hamzah Akhtar

||

Answers:

time.strftime("%b") 

will tell you the current month (abbreviation)

time.strftime("%m") 

will give you the numeric month (ie 1 = Jan / 12 = Dec)

(or even better)

datetime.datetime.now().month

as that will give you an actual integer instead of a string (be for-warned though January is 0)

Answered By: Joran Beasley

You can use datetime.datetime.now:

>>> from datetime import datetime
>>> datetime.now().month  # As a number
4
>>> datetime.now().strftime("%B")  # As a name
'April'
>>> datetime.now().strftime("%b")  # As an abbreviated name
'Apr'
>>>
Answered By: user2555451

whit import datetime
you can use datetime.date.today()
and return Current date or datetime

Answered By: roxdurazo

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'.

Answered By: Lily Mara
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.