Python - generate weekly date range from Saturday to Friday - python

I have a requirement to run a report on a weekly basis with week starting from Saturday and ending on Friday. However since the datetime or calendar module has week starting from Monday i couldn't use WEEKDAY option.
I tried the below option however it still gives me 5 for saturday,is there any options available to set weekstart day to Saturday so that for saturday it is 0 ? so that i can minus it from current date to get the desired dates or any other solution to acheive the same
Eg) If i run the report on August 30th it should fetch the data for August 18 to August 24
import calendar
calendar.setfirstweekday(calendar.SATURDAY)
calendar.firstweekday()
5

Thanks to the post Python: give start and end of week data from a given date slightly modified it based on my needs
dt = datetime.now()
start = (dt - timedelta(days = (dt.weekday() + 2) % 7)) - timedelta(days=7)
end = (start + timedelta(days=6))
print(start.strftime("%Y-%m-%d"))
print(end.strftime("%Y-%m-%d"))

It gives you 5 for Saturday, because 0 is Monday.
>>> calendar.setfirstweekday(calendar.MONDAY)
>>> calendar.firstweekday()
0

Related

Is the output week number string correct?

I'm trying to generate week number string using Python time module, considering week starts on Sunday.
If my interpretation of the official documentation is correct then this can be achieved by the following code:
import time
time.strftime("%U", time.localtime())
>> 37
My question is, is the above output correct? Shouldn't the output be 38 instead, considering the below details:
My timezone is IST (GMT+5:30)
import time
#Year
time.localtime()[0]
>> 2019
#Month
time.localtime()[1]
>> 9
#Day
time.localtime()[2]
>> 18
Yes, the output is correct. Week 1 started on January 6th, as that was the first Sunday in 2019. January 1st through 5th were week 0:
>>> time.strftime('%U', time.strptime("2019-1-1", "%Y-%m-%d"))
'00'
>>> time.strftime('%U', time.strptime("2019-1-6", "%Y-%m-%d"))
'01'
This is covered in the documentation:
All days in a new year preceding the first Sunday are considered to be in week 0.
You are perhaps looking for the ISO week date, but note that in this system the first day of the week is a Monday.
You can get the week number using that system with the datetime.date.isocalendar() method, or by formatting with %V:
>>> time.strftime("%V", time.localtime())
'38'
>>> from datetime import date
>>> date.today().isocalendar() # returns ISO year, week, and weekday
(2019, 38, 2)
>>> date.today().strftime("%V")
'38'
It's correct since you start counting from the first Sunday.
%U - week number of the current year, starting with the first Sunday as the first day of the first week
https://www.tutorialspoint.com/python/time_strftime.htm
It's correct. Since all days in a new year preceding the first Sunday are considered to be in week 0 (01/01 to 01/05), this week is the week 37.

I want to extract a certain dates from the calendar IN PYTHON please

I want to extract a certain dates from the calendar. For example, given the start date is 02/01/2017 and that day happens to be a Monday, I want to add the date to an empty list and if day in (Mon to Thurs), I want to add 8 days to that date and add that date to the list. If friday, add 3 days to the list.
Put it simply, if start date is monday, next tuesday, wednesday after that week and the thursday after and then friday ... each week, increment the day and add it to the list but if friday, add monday's date to the list.
The pandas package isn't necessary, but if you ever need to input a date via raw_input(), it is a good tool for handling formatting issues with just one line of code. (2016/12/12 vs. 12-12-16, etc.)
If I understand your question correctly, this should accomplish what you want:
from datetime import timedelta
import pandas as pd
dates = []
start_date = pd.to_datetime(raw_input('Enter Start Date: '))
dates.append(start_date.strftime('%x'))
if start_date.weekday() < 4:
add_date = start_date + timedelta(8)
dates.append(add_date.strftime('%x'))
elif start_date.weekday() == 4:
add_date = start_date + timedelta(3)
dates.append(add_date.strftime('%x'))
else:
print 'Error: Start Date is on a weekend.'
print dates

Getting the date of the first day of the week

I have records in a table which have a date field.
I would like to query the table so that the records returned are only the Sunday's date of a given week.
How could I use python's datetime library to achieve this? Thanks.
To get the beginning date of the week from Sunday:
datetime.today() - datetime.timedelta(days=datetime.today().isoweekday() % 7)
Thanks #PavSidhu and editors of that answer. Building further on that answer:
If your start of week is Sunday
import datetime
datetime.datetime.today() - datetime.timedelta(days=datetime.datetime.today().isoweekday() % 7)
If your start of week is Monday
import datetime
datetime.datetime.today() - datetime.timedelta(days=datetime.datetime.today().weekday() % 7)
If you want to calculate start of week for a future date
import datetime
from dateutil.relativedelta import relativedelta
# 5 days ahead of today
future_date = datetime.datetime.today() + relativedelta(days=5)
# If Start of Week is Monday
print(future_date - datetime.timedelta(days=future_date.weekday() % 7))
# If start of week is Sunday
print(future_date - datetime.timedelta(days=future_date.isoweekday() % 7))
Diff: When start of week is Monday, we are using weekday() instead of isoweekday()
isoweekday() - Monday is 1 and Sunday is 7
weekday() - Monday is 0 and Sunday is 6

Get week number using date in python

Date is datetime.date(2013, 12, 30)
I am trying to get week number using
import datetime
datetime.date(2013, 12, 30).isocalendar()[1]
I am getting output as ,
1
Why i am not getting week number of last year , instead i am getting week number of current year?
Whats wrong i am doing here ?
You are doing nothing wrong, 2013/12/30 falls in week 1 of 2014, according to the ISO8601 week numbering standard:
The ISO 8601 definition for week 01 is the week with the year's first Thursday in it.
The Thursday in that week is 2014/01/02.
Other ways to explain the definition, from the same linked WikiPedia article:
It is the first week with a majority (four or more) of its days in January (ISO weeks start on Monday)
Its first day is the Monday nearest to 1 January.
It has 4 January in it. Hence the earliest possible dates are 29 December through 4 January, the latest 4 through 10 January.
It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.
If you were looking for the last week number of a given year (52 or 53, depending on the year), I'd use December 28th, which is always guaranteed to be in the last week (because January 4th is always part of the first week of the next year):
def lastweeknumber(year):
return datetime.date(year, 12, 28).isocalendar()[1]
from datetime import date
from datetime import datetime
ndate='10/1/2016'
ndate = datetime.strptime(ndate, '%m/%d/%Y').strftime('%Y,%m,%d')
print('new format:',ndate)
d=ndate.split(',')
wkno = date(int(d[0]),int(d[1]),int(d[2])).isocalendar()[1]
print(wkno)
manually or read a date to a string and get the week number, play around with different formats.

Get Monday and Sunday and last year's Monday and Sunday, same week

Given datetime.datetime.now(), how do I get this week's Monday - Sunday and then the same Monday - Sunday for last year, considering leap years?
One idea I had was to get the timedelta for -365 days and then find the nearest Monday or Sunday. I'm sure there is a better way.
Edit: I don't mind using datetuil, if there is something in there that'd make this easier.
If using dateutil is not a problem, just use it :)
The relativedelta is the object you need
Here you will be able to substract one year to the current date.
from datetime import *
from dateutil.relativedelta import *
NOW = datetime.now()
last_monday = NOW+relativedelta(years=-1, weekday=MO)
last_sunday = NOW+relativedelta(years=-1, weekday=SU)
If this year's this Monday has date N, the same Monday last year would have a date N + 1 if there was no Feb 29 in between, otherwise last year's Monday would have a date N + 2.
from datetime import date, timedelta
today = date.today()
monday = today - timedelta(today.weekday())
sunday = monday + timedelta(6);
print monday, '-', sunday
monday_last_year = monday - timedelta(364) # We are trying to go to date N + 1.
if monday_last_year.weekday() == 1: # It will be either 0 or 1.
monday_last_year + timedelta(1) # This is date N + 2.
sunday_last_year = monday_last_year + timedelta(6)
print monday_last_year, '-', sunday_last_year
from datetime import date, timedelta
monday = date.today() - timedelta(days=date.today().weekday())
sunday = monday + timedelta(days=6)
The answer to the second question might depend on what counts as the 'same' monday-sunday. I'd start with the naive version and adjust if it it's not correct:
last_year_mon = monday - timedelta(weeks=52)
last_year_sun = last_year_mon + timedelta(days=6)
You can use .isocalendar() to retrieve the week number in the year, then from there derive the monday/sunday of that week for the current and previous year.
year, week, _ = datetime.datetime.now().isocalendar()
Then, using iso_to_gregorian from this answer:
this_sunday = iso_to_gregorian(year, week, 0)
this_monday = iso_to_gregorian(year, week, 1)
last_year_sunday = iso_to_gregorian(year - 1, week, 0)
last_year_monday = iso_to_gregorian(year - 1, week, 1)

Categories