Reputation: 525
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'
Upvotes: 6
Views: 15080
Reputation: 4138
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'
.
Upvotes: 10
Reputation:
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'
>>>
Upvotes: 5
Reputation: 775
whit import datetime
you can use datetime.date.today()
and return Current date or datetime
Upvotes: -1
Reputation: 114108
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)
Upvotes: 7