using week number to get range of dates with sunday as first day of week in python - python-3.x

input: week_number = 34 (or 2022-34)
expected output:
["2022-08-21","2022-08-22", "2022-08-23","2022-08-24","2022-08-25","2022-08-26","2022-08-27"]
First date should be of Sunday
the last date should be Saturday
work with both leap and non leap year

Try:
import datetime
week_number = 34
out = []
date = datetime.datetime.strptime(f"2022-{week_number}-0", "%Y-%U-%w")
for day in range(7):
out.append((date + datetime.timedelta(days=day)).strftime("%Y-%m-%d"))
print(out)
Prints:
[
"2022-08-21",
"2022-08-22",
"2022-08-23",
"2022-08-24",
"2022-08-25",
"2022-08-26",
"2022-08-27",
]
From the reference:
%U - Week number of the year (Sunday as the first day of the week) as
a zero-padded decimal number. All days in a new year preceding the
first Sunday are considered to be in week 0.

Related

Need to get output of all weekdays starting from given date

Output is not how it should be
given_day = datetime.date(2022,10,31)
dates = given_day + datetime.timedelta(days=+1)
for i in range(0 - given_day.weekday(), 7 - given_day.weekday()):
print(given_day.strftime("%A"))
Output should start from Monday and end to Sunday
Output I get is:
Monday
Monday
Monday
Monday
Monday
Monday
Monday
Where i made a mistake :(
I can't make head or tail of your code, but the following works:
given_day = datetime.date(2022,10,31)
for i in range(0 + given_day.weekday(), 7):
print(given_day.strftime("%A"))
given_day += datetime.timedelta(days=1)

find the last business date for June and Dec of any given year in Python

I want to find the last business day for the month of June and Dec for 2019. my below code gives me the last business day for last month and the current month. Ideally i want a code which allows me to input a year and month and it will tell me the last business day for the month and year i input.
i want my output to be like this for June 2019 and Dec 2019
2906
3112
hope someone can help me here, thanks
from pandas.tseries.offsets import BMonthEnd
from datetime import date
d=date.today()
offset = BMonthEnd()
#Last day of current month
current_month = offset.rollforward(d)
print(current_month)
#Last day of previous month
last_month = offset.rollback(d)
print(last_month)
Here's a function that will find the last weekday in a given month and format it as a string in the format given
import datetime
def last_weekday(year, month):
# Add a month
if month == 12:
month = 1
year += 1
else:
month += 1
d = datetime.date(year, month, 1)
# Subtract a day
d -= datetime.timedelta(days=1)
# Subtract more days if we have a weekend
while d.weekday() >= 5:
d -= datetime.timedelta(days=1)
return '{:02d}{:02d}'.format(d.month, d.day)
# Examples:
last_weekday(2019, 6) # -> '0628'
last_weekday(2019, 12) # -> '1231'

Pandas to recognize current date, and filter a date column relative to today's date

Having a lot of trouble translating the logic below in pandas/python, so I do not even have sample code or a df to work with :x
I run a daily report, that essentially filters for data from Monday thru the day before what 'Today' is. I have a Date column [ in dt.strftime('%#m/%#d/%Y') format] . It will never be longer than a Monday-Sunday scope.
1) Recognize the day it is 'today' when running the report, and recognize what day the closet Monday prior was. Filter the "Date" Column for the Monday-day before today's date [ in dt.strftime('%#m/%#d/%Y') format ]
2) Once the df is filtered for that, take this group of rows that have dates in the logic above, have it check for dates in a new column "Date2". If any dates are before the Monday Date, in Date2, change all of those earlier dates in 'Date2' to the Monday date it the 'Date' column.
3) If 'Today' is a Monday, then filter the scope from the Prior Monday through - Sunday in the "Date" Column. While this is filtered, do the step above [step 2] but also, for any dates in the "Date2" column that are Saturday and Sunday Dates - changes those to the Friday date.
Does this make sense?
Here're the steps:
from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d')
# if today is Monday, we need to step back another week
if day_of_week == 0:
last_monday -= pd.to_timedelta(7, unit='d')
# filter for last Monday
last_monday_flags = (df.Date == last_mon)
# filter for Date2 < last Monday
date2_flags = (df.Date2 < last_monday)
# update where both flags are true
flags = last_monday_flags & date2_flags
df.loc[flags, 'Date2'] = last_monday
# if today is Monday
if day_of_week == 0:
last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_week_flags = (df.Date >= last_monday) & (df.Date <= next_sunday)
last_sat_flags = (df.Date2 == last_sat)
last_sun_flags = (df.Date2 == last_sun)
# I'm just too lazy and not sure how Sat and Sun relates to Fri
# but i guess just subtract 1 day or 2 depending on which day
...

ValueError: day is out of range for month python

I am writing code that lets users write down dates and times for things they have on. It takes in the date on which it starts, the start time and finish time. It also allows the user to specify if they want it to carry over into multiple weeks (every Monday for a month for example)
I am using a for loop to do this, and because of the different months having different days I obviously want (if the next Monday for example is in the next month) it to have the correct date.
This is my code:
for i in range(0 , times):
day = day
month = month
fulldateadd = datetime.date(year, month, day)
day = day + 7
if month == ( '01' or '03' or '05' or '07' or '10'or '12'):
if day > 31:
print(day)
day = day - 31
print(day)
month = month + 1
elif month == ( '04' or '06'or '09' or '11'):
if day > 30:
print(day)
day = day - 30
print(day)
month = month + 1
elif month == '02':
if day > 29:
print(day)
day = day - 29
print(day)
month = month + 1
When running this and testing to see if it goes correctly into the new month I get the error:
File "C:\Users\dansi\AppData\Local\Programs\Python\Python36-32\gui test 3.py", line 73, in addtimeslot
fulldateadd = datetime.date(year, month, day)
ValueError: day is out of range for month
Where have I gone wrong?
It's hard to be completely accurate without seeing some of the previous code (for example, where do day, month, year, and times come from?), but here's how you might be able to use timedelta in your code:
fulldateadd = datetime.date(year, month, day)
for i in range(times):
fulldateadd = fulldateadd + datetime.timedelta(7)
A timedelta instance represents a period of time, rather than a specific absolute time. By default, a single integer passed to the constructor represents a number of days. So timedelta(7) gives you an object that represents 7 days.
timedelta instances can then be used with datetime or date instances using basic arithmetic. For example, date(2016, 12, 31) + timedelta(1) would give you date(2017, 1, 1) without you needing to do anything special.

Getting a day date for last week from a given date

I know how to get the last Saturday date using date --date="sat. last week" +"%m%d%Y" However, I am unable to get the last Saturday date for a particular given date.
I am trying to find the date of last saturday date from a given date. For an instance, let us say that the given date is 20140605 (in YYYYMMDD format) or any weekday date from that particular week. This given date could be any weekday date (20140602-20140606) in the following week for that Saturday, I need to derive the Saturday date for the week before this date which would be (in my case)= 20140531. How can I achieve this?
I just barfed a bit on my keyboard, but this seems to work:
D="20140605"; date --date "$D $[($(date --date "$D" +%u) + 1) % 7] days ago" +"%Y%m%d"
I have a small Python snippet for you:
from datetime import datetime, timedelta
import sys
fmt = "%Y%m%d"
daystring = sys.argv[1]
day = datetime.strptime(daystring, fmt)
for d in range(7):
# Go back a few days, but not more than 6.
testdate = day - timedelta(days=d)
# If the test date is a saturday (0 is monday, 6 sunday), output that date.
if testdate.weekday() == 5:
print testdate.strftime(fmt)
Test:
$ python test.py 20140605
20140531

Resources