I am new to python and I have an assignment to print month names with corresponding numbers.
How can I make an if statement with multiple conditions so I don't need to make twelve of them?
Normally it would be :
if month == 1
print(one) # one = January
Can I make it something like :
if month == [1,2,3,4,5,6]
print [one,two.three, etc.]
I tried it and it does not work, but I am wondering if it is possible?
You'd better save that in a dict, to get mappings month index -> month name
months = {1: "January", 2: "February"}
month = 1
if month in months:
print(months[month])
Or with calendar
import calendar
month = 1
if month in range(13):
print(calendar.month_name[month])
Use Dictionary
months = {1:"Jan", 2:"Feb", 3:"March" ... and so on}
if inputMonth in months:
print(months[inputMonth])
or you can use List
months = ["Jan", "Feb", "March"... ]
inputMonth = 1
if inputMonth in range(0,13):
print(months[inputMonth-1])
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Is there a function to determine which quarter of the year a date is in?
(18 answers)
Closed 1 year ago.
I am trying to def a function which will return the current quarter of the year in a string.
import datetime
date = datetime.datetime(2022,1,1)
month = date.month
year = date.year
if month ==1 or 2 or 3:
quarter = 'Q1'
if month ==4 or 5 or 6:
quarter = 'Q2'
if month ==7 or 8 or 9:
quarter = 'Q3'
if month ==10 or 11 or 12:
quarter = 'Q4'
lookup = quarter +str(year)
print(lookup)
when I run this function I get Q42022. Am I missing something in the if/or statements.
Any help would be greatly appreciated.
You have to explicitly specify
if month==1 or month==2 or month==3:
You could also check inclusion
if month in (1, 2, 3):
if month in {1, 2, 3}:
# and so on
I am new to scripting need some help in writing the code in correct way. I have a csv file in which we have date based on the date I need to create a new column name period which will be combination of year and month.
If the date range is between 1 to 25, month will be the current month from the date
If the date range is greater then 25, month will be next month.
Sample file:
Date
10/21/2021
10/26/2021
01/26/2021
Expected results:
Date
Period (year+month)
10/21/2021
202110
10/26/2021
202111
01/26/2021
202102
Two ways I can think of.
Convert the incoming string into a date object and get the values you need from there. See Converting string into datetime
Use split("/") to split the date string into a list of three values and use those to do your calculations.
Good question.
I've included the code that I wrote to do this, below. The process we will follow is:
Load the data from a csv
Define a function that will calculate the period for each date
Apply the function to our data and store the result as a new column
import pandas as pd
# Step 1
# read in the data from a csv, parsing dates and store the data in a DataFrame
data = pd.read_csv("filepath.csv", parse_dates=["Date"])
# Create day, month and year columns in our DataFrame
data['day'] = data['Date'].dt.day
data['month'] = data['Date'].dt.month
data['year'] = data['Date'].dt.year
# Step 2
# Define a function that will get our periods from a given date
def get_period(date):
day = date.day
month = date.month
year = date.year
if day > 25:
if month == 12: # if december, increment year and change month to jan.
year += 1
month = 1
else:
month += 1
# convert our year and month into strings that we can concatenate easily
year_string = str(year).zfill(4) #
month_string = str(month).zfill(2)
period = str(year_string) + str(month_string) # concat the strings together
return period
# Step 3
# Apply our custom function (get_period) to the DataFrame
data['period'] = data.apply(get_period, axis = 1)
I have a list of dates as generated by:
from dateutil import parser
from datetime import date, timedelta
d1 = parser.parse("2015-11-25")
d2 = parser.parse("2016-02-06")
delta = (d2-d1).days
date_list = [d1 + timedelta(days=x) for x in range(0, delta+1)]
In this list there are 6 days in the month of november 2015, 31 days in december 2015 , 31 days in january 2016 and 6 days in february 2016. December 2015 and January 2016 are "full" months, i.e. the datelist has all days in those months.
How can I get this information programatically in python, in order to produce a list such as:
[(2015,11,6,False),(2015,12,31,True),(2016,1,31,True),(2016,2,6,False)]
Found a neat short solution:
from dateutil import parser
from datetime import date, timedelta
from collections import Counter
from calendar import monthrange
d1 = parser.parse("2015-11-25")
d2 = parser.parse("2016-02-06")
delta = (d2-d1).days
date_list = [d1 + timedelta(days=x) for x in range(0, delta+1)]
month_year_list = [(d.year, d.month) for d in date_list]
result = [(k[0],k[1],v , True if monthrange(k[0], k[1])[1] == v else
False) for k,v in Counter(month_year_list).iteritems()]
print result
Walk the list and accumulate the number of days for each year/month combination:
import collections
days_in_year_month = defaultdict(int)
for each_date in date_list:
days_in_year_month[(each_date.year, each_date.month)] += 1
Next output the tuples with each year, month, count and T/F:
import calendar
result = []
for year_month in date_list.keys():
days_in_ym = days_in_year_month([year_month[0], year_month[1])
is_complete = days_in_ym == calendar.monthrange(year_month[0], year_month[1])[1]
result.append(year_month[0], year_month[1], days_in_ym, is_complete)
So:
I learned about monthrange here: How do we determine the number of days for a given month in python
My solution sucks because it will do a total of 3 loops: the initial loop from your list comprehension, plus the two loops I added. Since you're walking the days in order for your list comprehension, this could be much optimized to run in a single loop.
I didn't test it :)
The previous mentioned solutions seem ok, however I believe I have a more optimal solution, since they require to calculate a list that contains all the days. For a small date difference this won't be problematic. However if the difference increases, your list will become a lot larger.
I want to give another approach that is more intuitive, since you basically know that all months that between the dates are full, and the months of the dates themselves are not full.
I try to leverage that information and the loop will only iterate the amount of months between the dates.
The code:
from dateutil import parser
from calendar import monthrange
d1 = parser.parse("2015-11-25")
d2 = parser.parse("2016-02-06")
# needed to calculate amount of months between the dates
m1 = d1.year * 12 + (d1.month- 1)
m2 = d2.year * 12 + (d2.month - 1)
result = []
# append first month since this will not be full
result.append((d1.year,d1.month,monthrange(d1.year, d1.month)[1]-d1.day+1,False))
current_month = d1.month
current_year = d1.year
# loop through the months and years that follow d1.
for _ in xrange(0,(m2-m1)-1):
if current_month+1 > 12:
current_month = 1
current_year += 1
else:
current_month += 1
result.append((current_year,current_month,monthrange(current_year, current_month)[1],True))
# append last month since this will not be full either.
result.append((d2.year,d2.month,d2.day,False))
print result
Keep in mind that the code I gave is an example, it doesn't support for instance the scenario where the 2 given dates have the same month.
I am trying to write a Python script that will calculate how many business days are in the current month. For instance if month = August then businessDays = 22.
Here is my code for discovering the month:
def numToMonth( num ):
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
return str(months[ num - 1 ])
This code works fine, and I could hard code another function to match the month with how many days that month should contain...but this does not help me with business days.
Any help? I'm used to C, C++ so please don't bash my Python "skills".
Edit: I cannot install any extra libraries or modules on my machine, so please post answers using default Python modules. (Python 2.7, datetime etc.) Also, my PC has Windows 7 OS.
This is a long-winded way, but at least it works and doesn't require anything other than the standard modules.
import datetime
now = datetime.datetime.now()
holidays = {datetime.date(now.year, 8, 14)} # you can add more here
businessdays = 0
for i in range(1, 32):
try:
thisdate = datetime.date(now.year, now.month, i)
except(ValueError):
break
if thisdate.weekday() < 5 and thisdate not in holidays: # Monday == 0, Sunday == 6
businessdays += 1
print businessdays
I would simply use built-in module calendar:
import calendar
weekday_count = 0
cal = calendar.Calendar()
for week in cal.monthdayscalendar(2013, 8):
for i, day in enumerate(week):
# not this month's day or a weekend
if day == 0 or i >= 5:
continue
# or some other control if desired...
weekday_count += 1
print weekday_count
that's it.
I would like to add my answer.
I'm using Calendar, list comprehension, and length to count how many days is the working day a particular month.
Here is my code:
#!/bin/env python
import calendar
import datetime
now = datetime.datetime.now()
cal = calendar.Calendar()
working_days = len([x for x in cal.itermonthdays2(now.year, now.month) if x[0] !=0 and x[1] < 5])
print "Total working days this month: " + str(working_days)
I stole this from Sharuzzaman's solution and added a dict for holidays and turned it into a function:
import calendar
cal = calendar.Calendar()
def get_wdim(year,month):
working_days = len([x for x in cal.itermonthdays2(year, month) if x[0] !=0 and x[1] < 5])
holidays = {
1:1,
2:1,
4:1,
5:1,
7:1,
9:1,
10:1,
11:4,
12:1
}
return int(working_days) - holidays.get(month,0)
wdim2022 = [get_wdim(2022,x) for x in list(range(1,13)) ]
UPDATE: OP can't use any external libraries. Then you will have to build some tables based on determining the day of the week from the calendar.
The formula is d + m + y + y/4 + (c mod 7), where: d is the day of the month,
m is the month's number in the months table,
y is the last two digits of the year, and
c is the century number.
It's tedious but not impossible!
ORIG answer: It's quite tedious to code yourself, because August 01, 2013 and August 01, 2012 are not necessarily the same day of the week. I'd start with the 'date' class in python (details here
from datetime import date
datetime.date(2002, 3, 11)
t = d.timetuple()
for i in t:
print i
In particular, check out the 'datetime.weekday()' function.
This is relatively simple, just break it down into steps:
You need to be able to loop through the days in a month.
You need to be able to determine the day of a week that any given date falls on. Wikipedia lists some methods.
Then you need only flag days of the week as business days or not.
Combine these steps and you'll have a working method.
You could take a look at datetime.datetime.dayofweek() but if you are not allowed to use an external library then you need to:
pick a date that you know the day of week of - best if it is a
Monday
come up with a formulae for the number of days since then that the
first of a given month is.
for each of the days in the month the (number of days since your
day) % 7 in [5, 6] is a weekend.
Acknowledging the OP stated external libraries could not be used, given the ranking of the question in searches (together with the fact this wasnt stated in the title), I figured I'd share a pandas solution which provides a solution spanning multiple months, with results presented in a df.
import pandas as pd
business_days = pd.date_range(start, end, freq='B')
pd.DataFrame(index=business_days, data=[1] * len(business_days)).resample('M').sum()
I am new to python and only know the most basic level.
I am supposed to allow input of a date in the form of dd/mm/yyyy and convert it to something like 26 Aug, 1986.
I am stuck as to how to convert my month(mm) from numbers to words.
Below is my current code, hope you can help me.
** please do not suggest using calendar function, we are supposed to use dict to solve this question.
Thank you (:
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[:2]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
month=date[3:5]
if month in monthDict:
for key,value in monthDict:
month=value
#year
year=date[4:]
#print the result in the required format
print day, month, "," , year
Use Python's datetime.datetime! Read using my_date = strptime(the_string, "%d/%m/%Y"). Print it using my_date.strftime("%d %b, %Y").
Visit: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Example:
import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011
date = raw_input("Please enter the date in the format of dd/mm/year: ")
date = date.split('/')
day = date[0] # date is, for example, [1,2,1998]. A list, because you have use split()
monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',
7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
month = date[1] # Notice how I have changed this as well
# because the length of date is only 3
month = monthDict[int(month)]
year = date[2] # Also changed this, otherwise it would be an IndexError
print day, month, "," , year
When run:
Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
After you have done split, you don't need to use index like day=date[:2]. Simply use say = date[0]. Similarly no looping is required to match dictionary values. You can see the code below.
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[0]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
monthIndex= int(date[1])
month = monthDict[monthIndex]
#year
year=date[2]
print day, month, "," , year
When you split your date string, you will only have three elements (0, 1, and 2):
>>> date=date.split('/')
>>> print date
['11', '12', '2012']
^ ^ ^
0 1 2
Thus, date[:2] will equal this:
>>> day=date[:2] # that is, date up to (but not including) position 2
>>> print day
['11', '12']
And date[4] will not exist, and neither will date[3:5].
In addition, you need to call your dictionary value like this:
>>> print monthDict[12]
Dec
So to print the day, month, year combination, you would want to do this:
>>> print date[0], monthDict[int(date[1])] + ", " + date[2]
11 Dec, 2012
You have to use int(date[0]) as your key in monthDict[int(date[0])] because you used integers as your dictionary keys. But your input (from the user) is a string, not integers.