Dates out of order - python

Why does it starts with december? And 1 1 repeats at the end. Whats the more Pythonic way to iterate over all days in a given year (with handling the leap year)?
import calendar
a = calendar.Calendar(0)
for b in range(1,13):
for x in a.itermonthdates(2016,b):
print x.month, x.day
Output:
12 28
12 29
12 30
12 31
1 1
1 2
1 3
..
..
..
Full Output:
http://pastebin.com/nnP4ADQK

itermonthdates returns complete weeks:
itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.
You could just reject the dates where year is not 2016:
import calendar
a = calendar.Calendar(0)
g = (x for b in xrange(1, 13) for x in a.itermonthdates(2016, b) if x.year == 2016)
print next(g)
Output:
2016-01-01

itermonthdates
returns all weeks which includes days of month. So check should be done for all months.
import calendar
a = calendar.Calendar(0)
for b in range(1,13):
for x in a.itermonthdates(2017,b):
if x.month==b:
print x #x.month, x.day

Related

First weekday of the year (without weekends)

Can anyone help me get the first weekday (as a date) of a given year in Python?
This gives me the first Monday of the current week:
test = datetime.today() - timedelta(days=datetime.today().isoweekday() % 7)
print(test)
This is easy once you break it down:
Let's define a function that takes an input yr and returns the first weekday of that year.
def first_weekday(yr: int) -> datetime.date:
What is the first day of the year yr?
first_day = datetime.date(yr, 1, 1)
Is that day a weekday? If so, it is the first weekday of the year.
day_of_week = first_day.isoweekday()
if day_of_week < 6: return first_day
datetime.date.isoweekday() returns 1 for Monday and 7 for Sunday.
Why did I use isoweekday instead of weekday? No reason
If not, find how many days until Monday. Subtracting the day_of_week from 8 should do the trick!
We would subtract from 7 for weekday().
days_to_monday = 8 - day_of_week
first_weekday = first_day + datetime.timedelta(days=days_to_monday)
return first_weekday
Put this all together, and test:
for yr in range(2019, 2025):
print(yr, first_weekday(yr))
prints:
2019 2019-01-01
2020 2020-01-01
2021 2021-01-01
2022 2022-01-03
2023 2023-01-02
2024 2024-01-01

How can i find all 'friday the 13th' due year 2000 to 2020 by python

How can i find all 'friday the 13th' due year 2000 to 2020 by python and have it print as below using a nested for loop:
print(i,k,13,"is friday the 13th!")
ex)
2000 10 13 is friday the 13th!
2001 4 13 is friday the 13th!
...
2020 11 13 is friday the 13th!
Based on your code in the comments, this should work for you:
from datetime import date, timedelta
def friday_13_in_year(y):
day = date(y, 1, 1)
end = date(y, 12, 31)
one_day = timedelta(days=1)
while day < end:
if day.weekday() == 4 and day.day == 13:
return str(day)+" is friday the 13th!"
day += one_day
print([friday_13_in_year(y) for y in range(2000, 2022+1)])
l=[i for i in ((datetime.datetime.strptime('20000101','%Y%m%d')+datetime.timedelta(days=i)) for i in range(7306)) if i.day == 13 and i.weekday() == 4]
l lists all Fridays 13th from 2000 to 2020. 20 years in days is 20*365.25+1 = 7306

Print specific date in python

I want to create a function that will return a date depending on each month. More specific I want it to return to me the 23d day of each month in the example format (YYYY, MM, DD):
2018, 1, 23 .
except for the occasion that this date coincides with a weekend, in which I want it to return the exact previous working day. For example for December 2017 the 23d was Saturday, so in this case I want my function to return to me
2017, 12, 22.
Right now I use:
import datetime
someday = datetime.date(2018, 1, 23)
print(someday)
with which in the someday variable I define the desired date manually for each month.
In short for the next seven months of 2018 (January, February, March, April, May, June, July), I want my function to return to me :
2018, 1, 23
2018, 2, 23
2018, 3, 23
2018, 4, 23
2018, 5, 23
2018, 6, 22
2018, 7, 23
and so on and so forth for the next months.
You can achieve this with weekday(), timedelta() and while loop:
from datetime import date, timedelta
def last_workday(somedate):
while somedate.weekday() > 4: #weekday returns values 0-6 (Mon-Sun)
somedate -= timedelta(days=1) #timedelta returns 1 day which you subtract from your date
return somedate
y = 2018
d = 23
for m in range(1,13):
print(last_workday(date(y, m, d)))
I wrote a small python script on how you could do it.
Use toordinal to check for the day of the week and if it's Saturday or Sunday, subtract 1 or 2 by using timedelta
import datetime
# Yes, from 1,13 because 13 is exclusive (Goes only to 12)
days_month = datetime.monthrange(2018,x)
for x in range(days_month[0],days_month[1]+1):
for x in range(1, monthrange):
someday = datetime.date(2018, x, 23) # Loop over every month
weekday = someday.weekday() # 0 = Monday, 6 = Sunday
if(weekday > 5 ): # If it's "more" than Friday
jumpback_days = weekday - 4; # Subtract 4 from the current weekday to get 1 for Saturday and 2 for Sunday
print(someday - datetime.timedelta(days=jumpback_days)) # Subtract days and print
else:
# Print without subtracting anything
print(someday)
Note: If you are using Python2, please replace range with xrange for it to work.
EDIT: If you want to print only and all workdays in a specific year, you can do it this way:
import datetime
from calendar import monthrange
year = 2018
for month in range(1, 13): # Yes, from 1,13 because 13 is exclusive (Goes only to 12)
days_month = monthrange(year, month) # Request the amount of days in that month
for day in range(1, days_month[1] + 1): # Iterate through all days of that month (+1 because it's exclusive)
someday = datetime.date(year, month, day) # Loop over every month
weekday = someday.weekday() # 0 = Monday, 6 = Sunday
if(weekday < 5 ): # If it's "less" than Saturday
# Print because if it's "less" than Saturday, then it's a workday
print(someday)

Trying to make a program that displays days in a month

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

Week Number for Actual Calendar Python

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

Categories

Resources