I'm trying to write a program that shows the days in a month when you type the number that corresponds to the month.
Ex. 1 = January, would print "31"
This is what I have and it seems logical to me. Although I'm just over a month into this and I have no idea what I'm doing.
def calcDaysInMonth():
(list,(range,(1, 12)))
a = raw_input()
int(a)
jan = 1
feb = 2
mar = 3
apr = 4
may = 5
june = 6
july = 7
aug = 8
sept = 9
octo = 10
nov = 11
dec = 12
if jan is True:
print("31")
using static number wont help you get correct result. because Feb days in leap year is different than normal. so use
$Year = 2017
$month = 08`
echo cal_days_in_month(CAL_GREGORIAN, (int)$month, $Year);
The reason your code isn't working is because you're assigning the input to a but you're never checking the value of a and using that to determine what should be printed (you're simply assigning integers to variables called jan, feb etc)
You're looking for something like this:
a = int(raw_input())
if a == 1:
print("31 days")
elif a == 2:
print("28 days")
# just repeat with elif until december/12
You could try to get clever with it with dictionaries to map months to days or something, but really a more sensible solution would be the following...
Due to February having a different number of days given leap years, it makes more sense to just use calendar.monthrange to get the number of days in a month for any given year:
from calendar import monthrange
year = 2017
a = int(raw_input())
num_days = monthrange(year, a)[1]
print("{} days".format(num_days))
Thank you for all your help guys.
My class now has an answer for what we were doing. What was wanted:
month = int(raw_input())
day = 0
def calcDays(month):
if month ==1:
days = 31
print 31
if month==2:
days = 28
print 28
if month == 3:
days = 31
print 31
if month == 4:
days = 30
print 30
if month==5:
days = 31
print 31
if month ==6:
days = 30
print 30
if month==7:
days = 31
print 31
if month ==8:
days = 31
print 31
if month==9:
days = 30
print 30
Related
I'm teaching myself python to ATBS. Instead of spending 45 minutes typing out a bunch of repetitive data in excel I've spent the past 90 failing to write a simple calendar script.
Starting with the values "2012-09-01" and "2012-09-30" I want to each line to increase the month value by 1 it hits 12 and at which point the year value advances by 1, until the date 2018-12-31.
e.g.
"2012-09-01 2012-09-30
2012-10-01 2012-10-31
2012-11-01 2012-11-30
2012-12-01 2012-12-31"
Here's my code, which stops at 2012-12-31.
import datetime
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
Any help is much appreciated!
Check this out. Using the calendar library to detect leap years.
import datetime
import calendar
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
elif month == 2:
day_end = 29 if calendar.isleap(year) else 28
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
month = 1
Line
if month == 4 or month == 6 or month == 9 or month == 11:
can be abbreviated to:
if month in (4, 6, 9, 11):
Write a function that accepts a string which contains a particular
date from the Gregorian calendar. Your function should return what day
of the week it was. Here are a few examples of what the input
string(Month Day Year) will look like. However, you should not
'hardcode' your program to work only for these input!
"June 12 2012"
"September 3 1955"
"August 4 1843"
Note that each item (Month Day Year) is separated by one space. For
example if the input string is:
"May 5 1992"
Then your function should return the day of the week (string) such as:
"Tuesday"
Algorithm with sample example:
# Assume that input was "May 5 1992"
day (d) = 5 # It is the 5th day
month (m) = 3 # (*** Count starts at March i.e March = 1, April = 2, ... January = 11, February = 12)
century (c) = 19 # the first two characters of the century
year (y) = 92 # Year is 1992 (*** if month is January or february decrease one year)
# Formula and calculation
day of the week (w) = (d + floor(2.6m - 0.2) - 2c + y + floor(y/4) + floor(c/4)) modulo 7
after calculation we get, (w) = 2
Count for the day of the week starts at Sunday, i.e Sunday = 0, Monday = 1, Tuesday = 2, ... Saturday = 6
Since we got 2, May 5 1992 was a Tuesday
My first question is how do I accept June 12 2012 as input from the user? Is there any method that allows me to do this? Any help would be appreciated.
user_input = input('Enter the date')
Can someone tell me how to get a week number in Python for actual calendar.
Ex: 2016-01-01 to 2016-01-07 = week 1
2016-01-08 to 2016-01-14 = week 2
I tried 2 ways but none of them are working
Using isocalendar()
But that does not work for year end and year start week. For ex:
datetime.date(2016,01,01).isocalendar()[1]
# should be: 1
# got 53
is the following:
dt = date(2016,01,02)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 00
dt = date(2016,01,03)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 01
Both the ways do not satisfy my requirement. Is there any other library I can use to get the week number in Actual Calendar ?
Are you talking about actual number of 7 day periods rather than which week number you're in? Keep in mind in 2016, Jan 3rd is the first day of the second week.
If you're looking at which 7 day period, you should simply count days since the beginning of the year and floor div by 7
dt = datetime.datetime(year=2016, month=1, day=2)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
The 29th should be the first day of week 5. Let's try it.
dt = datetime.datetime(year=2016, month=1, day=29)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
# 5
I'm writing a program where the user will input 3 numbers the day month and year and it will output in the format 2nd January 2014. So far i have done this
year =input("what year is it")
month=int(input("what is the numerical value of the month"))
day=input("what number day is it")
if month == 1:
January = str(month)
if day == 1 or 21 or 31:
print (day+"st January",year)
elif day == 2 or 22:
print (day+"nd January",year)
elif day ==3 or 23:
print (day+"rd January",year)
elif day == 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 18 or 19 or 20 or 24 or 25 or 26 or 27 or 28 or 29 or 30:
print (day+"th January",year)
the problem i have run into is that when i input a day such as 4 it will ouput as 4st January 2014.
I am using python 3 and have learnt for and while loops and also if statements if that helps
Use the libraries and dictionaries, a good rule to remember is if you need more than two ifs a dictionary might be better.
from datetime import date
ext_dir = {1:'st.', 2:'nd.', 3:'rd.',
21:'st.', 22:'nd.', 23:'rd.',
31:'st.' } # all the rest are th
# prompt for the year month day as numbers remember to int them
thedate = date(year, month, day)
ext = ext_dir.get(day, 'th.')
datestr = thedate.strftime('%%d%s %%M %%Y' % ext)
The problem you are running in to is that when you perform the check:
if day == 1 or 21 or 31:
operator precedence in python makes this statement act something like this:
if (day == 1) or (21) or (31):
and in python, like many other languages, non-null/non-zero values are "true", so you always evaluate to true in the first test. To fix this, modify the if statement, and all of the following tests to look more like the following:
if (day == 1) or (day == 21) or (day == 31):
year =input("what year is it")
month=int(input("what is the numerical value of the month"))
day=input("what number day is it")
if month == 1:
January = str(month)
if day == 1 or day == 21 or day == 31:
print (day+"st January",year)
elif day == 2 or day == 22:
print (day+"nd January",year)
elif day ==3 or day == 23:
print (day+"rd January",year)
else:
print (day+"th January",year)
I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.
I tried getting the week number using d1.isocalendar()[1] and subtracting d2.isocalendar()[1] but the issue is that isocalendar()[1] returns December 31, 2012 as week 1 (which supposedly is correct) but that means my logic cannot span over this date.
For reference, here's my complete code:
def week_no(self):
ents = self.course.courselogentry_set.all().order_by('lecture_date')
l_no = 1
for e in ents:
if l_no == 1:
starting_week_of_year = e.lecture_date.isocalendar()[1] # get week of year
initial_year = e.lecture_date.year
if e == self:
this_year = e.lecture_date.year
offset_week = (this_year - initial_year) * 52
w_no = e.lecture_date.isocalendar()[1] - starting_week_of_year + 1 + offset_week
break
l_no += 1
return w_no
With this code, the lecture on Dec 31, 2012 ends up being -35.
How about calculating the difference in weeks between the Mondays within weeks of respective dates? In the following code, monday1 is the Monday on or before d1 (the same week):
from datetime import datetime, timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
print 'Weeks:', (monday2 - monday1).days / 7
Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.
You may want to refer the Python CookBook (2005 edition) Recipe 3.3. The following code snippet is from the cookbook, does what you require.
from dateutil import rrule
import datetime
def weeks_between(start_date, end_date):
weeks = rrule.rrule(rrule.WEEKLY, dtstart=start_date, until=end_date)
return weeks.count()
This is a very simple solution with less coding everyone would understand.
from datetime import date
d1 = date(year, month, day)
d2 = date(year, month, day)
result = (d1-d2).days//7
The solution above has a bug (I can't add a comment due to low reputation). It doesn't account for hour differences.
# This code has a bug.
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
Counter example of 2 dates more than a week apart:
Timestamp1: 1490208193270795 (22 Mar 2017 18:43:13 GMT)
Monday1: 20 Mar 2017 18:43:13 GMT
Timestamp2: 1489528488744290 (14 Mar 2017 21:54:48 GMT)
Monday2: 13 Mar 2017 21:54:48 GMT
Using that code it returns 0 as week diff when it should be 1. Need to zero out the hours/minutes/seconds as well.
To determine how many weeks are spanned by two dates. eg From 3rd Oct to 13th Oct
October 2015
Mo 5 12 19 26
Tu 6 13 20 27
We 7 14 21 28
Th 1 8 15 22 29
Fr 2 9 16 23 30
Sa 3 10 17 24 31
Su 4 11 18 25
Code:
import math, datetime
start_date = datetime.date(2015, 10, 3)
start_date_monday = (start_date - datetime.timedelta(days=start_date.weekday()))
end_date = datetime.date(2015, 10, 13)
num_of_weeks = math.ceil((end_date - start_date_monday).days / 7.0)
Equals 3 weeks.
You're a bit vague on what 'difference in weeks' means exactly. Is 6 days difference one week or zero ? Is eight days difference one week or two ?
In any case, why can't you simply find the difference in another unit (seconds or days) and divide by the appropriate amount, with your prefered rounding for weeks?
Edited Best Answer
from datetime import timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
diff = monday2 - monday1
noWeeks = (diff.days / 7) + math.ceil(diff.seconds/86400)
print('Weeks:', noWeeks)`