write a function that generates a list of last days of each month for the past n months from current date - date

I am trying to create a list of the last days of each month for the past n months from the current date but not including current month
I tried different approaches:
def last_n_month_end(n_months):
"""
Returns a list of the last n month end dates
"""
return [datetime.date.today().replace(day=1) - datetime.timedelta(days=1) - datetime.timedelta(days=30*i) for i in range(n_months)]
somehow this partly works if each every month only has 30 days and also not work in databricks pyspark. It returns AttributeError: 'method_descriptor' object has no attribute 'today'
I also tried the approach mentioned in Generate a sequence of the last days of all previous N months with a given month
def previous_month_ends(date, months):
year, month, day = [int(x) for x in date.split('-')]
d = datetime.date(year, month, day)
t = datetime.timedelta(1)
s = datetime.date(year, month, 1)
return [(x - t).strftime('%Y-%m-%d')
for m in range(months - 1, -1, -1)
for x in (datetime.date(s.year, s.month - m, s.day) if s.month > m else \
datetime.date(s.year - 1, s.month - (m - 12), s.day),)]
but I am not getting it correctly.
I also tried:
df = spark.createDataFrame([(1,)],['id'])
days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))
I got the last three months (Sep, oct, nov), but all of them are the 30th but Oct has Oct 31st. However, it gives me the correct last days when I put more than 3.
What I am trying to get is this:
(last days of the last 4 months not including last_day of current_date)
daterange = ['2022-08-31','2022-09-30','2022-10-31','2022-11-30']

Not sure if this is the best or optimal way to do it, but this does it...
Requires the following package since datetime does not seem to have anyway to subtract months as far as I know without hardcoding the number of days or weeks. Not sure, so don't quote me on this....
Package Installation:
pip install python-dateutil
Edit: There was a misunderstanding from my end. I had assumed that all dates were required and not just the month ends. Anyways hope the updated code might help. Still not the most optimal, but easy to understand I guess..
# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
def previous_month_ends(months_to_subtract):
# get first day of current month
first_day_of_current_month = date.today().replace(day=1)
print(f"First Day of Current Month: {first_day_of_current_month}")
# Calculate and previous month's Last date
date_range_list = [first_day_of_current_month - relativedelta(days=1)]
cur_iter = 1
while cur_iter < months_to_subtract:
# Calculate First Day of previous months relative to first day of current month
cur_iter_fdom = first_day_of_current_month - relativedelta(months=cur_iter)
# Subtract one day to get the last day of previous month
cur_iter_ldom = cur_iter_fdom - relativedelta(days=1)
# Append to the list
date_range_list.append(cur_iter_ldom)
# Increment Counter
cur_iter+=1
return date_range_list
print(previous_month_ends(3))
Function to calculate date list between 2 dates:
Calculate the first of current month.
Calculate start and end dates and then loop through them to get the list of dates.
I have ignored the date argument, since I have assumed that it will be for current date. alternatively it can be added following your own code which should work perfectly.
# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
def gen_date_list(months_to_subtract):
# get first day of current month
first_day_of_current_month = date.today().replace(day=1)
print(f"First Day of Current Month: {first_day_of_current_month}")
start_date = first_day_of_current_month - relativedelta(months=months_to_subtract)
end_date = first_day_of_current_month - relativedelta(days=1)
print(f"Start Date: {start_date}")
print(f"End Date: {end_date}")
date_range_list = [start_date]
cur_iter_date = start_date
while cur_iter_date < end_date:
cur_iter_date += timedelta(days=1)
date_range_list.append(cur_iter_date)
# print(date_range_list)
return date_range_list
print(gen_date_list(3))
Hope it helps...Edits/Comments are welcome - I am learning myself...

I just thought a work around I can use since my last codes work:
df = spark.createDataFrame([(1,)],['id'])
days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))
is to enter -4 and just remove the last_date that I do not need days.pop(0) that should give me the list of needed last_dates.

from datetime import datetime, timedelta
def get_last_dates(n_months):
'''
generates a list of lastdates for each month for the past n months
Param:
n_months = number of months back
'''
last_dates = [] # initiate an empty list
for i in range(n_months):
last_dates.append((datetime.today() - timedelta(days=i*30)).replace(day=1) - timedelta(days=1))
return last_dates
This should give you a more accurate last_days

Related

How do you find the first date of the week in SAS from a date?

I have a variable in a SAS dataset that has a number of dates (e.g. 01APR21). What I'm looking to do is create a new variable that shows the date of the first Monday of that week. So using the above example of 01APR21, the output would be 29/03/2021 as that what was when the Monday in that week was. I'm assuming it's using intnx, but I can't get my head around it.
data test;
format date date8.;
format first_day date10.;
date = '01APR21'd;
first_day = ?;
run;
INTNX Parameters:
Interval : WEEK
Increment: 0 (same week)
Alignment: Beginning
(Sunday)
Then add 1 to get to Monday instead of Sunday. You could probably play with the SHIFT INDEX parameter as well.
Monday = intnx('week', dateVariable, 0, 'B') + 1

JMeter: How to get date of last week starting from sunday till saturday?

The scenario is I need to get last week date in format yyyy-mm-dd HH:mm:ss from last Sunday till Saturday(date will increment by 1 from last week of Sunday till Saturday) and like wise one more is to get date from past 20 weeks(till last week).
How may I get it?
Your requirement is not very clear so I can provide only a generic solution:
Getting the "last Sunday"
def calendar = Calendar.instance
def delta = Calendar.SUNDAY - calendar.get(Calendar.DAY_OF_WEEK)
calendar.add(Calendar.DAY_OF_WEEK, delta)
log.info('Last Sunday: ' + calendar.time.format("yyyy-MM-dd HH:mm:ss"))
Getting all previous "dates" for last 20 weeks:
def now = new Date()
use(groovy.time.TimeCategory) {
def twentyWeeksAgo = now - 30.weeks
def duration = now - twentyWeeksAgo
1.upto(duration.days, {
twentyWeeksAgo = twentyWeeksAgo + 1.days
log.info(twentyWeeksAgo.format('yyyy-MM-dd HH:mm:ss'))
})
}
More information:
Groovy TimeCategory
Creating and Testing Dates in JMeter - Learn How

Qlikview - arrayList

i need to calculate difference between two date excluding sunday. I have table with dates and i need to calculate number of dates of repeated days from last date.
if i have dates like that
27-05-2017
29-05-2017
30-05-2017
I use this code in script
date(max(Date)) as dateMax,
date(min(Date)) as dateMin
And i get min date = 27-05-2017 and max date = 30-05-2017 then i use in expressions
=floor(((dateMax - dateMin)+1)/7)*6 + mod((dateMax - dateMin)+1,7)
+ if(Weekday(dateMin) + mod((dateMax - dateMin)+1,7) < 7, 0, -1)
And get result 3 days. Thats OK, but the problem is if I have next dates:
10-05-2017
11-05-2017
27-05-2017
29-05-2017
30-05-2017
When use previously code I get min date = 10-05-2017 and max date = 30-05-2017 and result 18, but this is not OK.
I need to count only dates from
27-05-2017
29-05-2017
30-05-2017
I need to get max date and go throw loop repeated dates and if have brake to see is that date sunday if yes then step that date and continue to count repeated dates and if i again have break and if not sunday than close loop and remember number of days.
In my case instead of 18 days i need to get 3 days.
Any idea?
I'd recommend you creating a master calendar in the script where you can apply weights or any other rule to your days. Then in your table or app you can just loop through the dates or perform operations and sum their weights (0: if sunday, 1: if not). Let's see an example:
// In this case I'll do a master calendar of the present year
LET vMinDate = Num(MakeDate(year(today()),1,1));
LET vMaxDate = Num(MakeDate(year(today()),12,31));
Calendar_tmp:
LOAD
$(vMinDate) + Iterno() - 1 as Num,
Date($(vMinDate) + Iterno() - 1) as Date_tmp
AUTOGENERATE 1 WHILE $(vMinDate) + Iterno() - 1 <= $(vMaxDate);
Master_Calendar:
LOAD
Date_tmp AS Date,
Week(Date_tmp) as Week,
Year(Date_tmp) as Year,
Capitalize(Month(Date_tmp)) as Month,
Day(Date_tmp) as Day,
WeekDay(Date_tmp) as WeekDay,
if(WeekDay = '7',0,1) as DayWeight //HERE IS WHERE YOU COULD DEFINE A VARIABLE TO DIRECTLY COUNT THE DAY IF IT IS NOT SUNDAY
'T' & ceil(num(Month(Date_tmp))/3) as Quarter,
'T' & ceil(num(Month(Date_tmp))/3) & '-' & right(year(Date_tmp),2) as QuarterYear,
date(monthStart(Date_tmp),'MMMM-YYYY') as MonthYear,
date(monthstart(Date_tmp),'MMM-YY') as MonthYear2
RESIDENT Calendar_tmp
ORDER BY Date_tmp ASC;
DROP Table Calendar_tmp;

convert year-month string into daily dates

recently I asked how to convert calendar weeks into a list of dates and received a great and most helpful answer:
convert calendar weeks into daily dates
I tried to apply the above method to create a list of dates based on a column with "year - month". Alas i cannot make out how to account for the different number of days in different months.
And I wonder whether the package lubridate 'automatically' takes leap years into account?
Sample data:
df <- data.frame(YearMonth = c("2016 - M02", "2016 - M06"), values = c(28,60))
M02 = February, M06 = June (M11 would mean November, etc.)
Desired result:
DateList Values
2016-02-01 1
2016-02-02 1
ect
2016-02-28 1
2016-06-01 2
etc
2016-06-30 2
Values would something like
df$values / days_in_month()
Thanks a million in advance - it is honestly very much appreciated!
I'll leave the parsing of the line to you.
To find the last day of a month, assuming you have GNU date, you can do this:
year=2016
month=02
last_day=$(date -d "$year-$month-01 + 1 month - 1 day" +%d)
echo $last_day # => 29 -- oho, a leap year!
Then you can use a for loop to print out each day.
thanks to answer 6 at Add a month to a Date and answer for (how to extract number with leading 0) i got an idea to solve my own question using lubridate. It might not be the most elegant way, but it works.
sample data
data <- data_frame(mon=c("M11","M02"), year=c("2013","2014"), costs=c(200,300))
step 1: create column with number of month
temp2 <- gregexpr("[0-9]+", data$mon)
data$monN <- as.numeric(unlist(regmatches(data$mon, temp2)))
step 2: from year and number of month create a column with the start date
data$StartDate <- as.Date(paste(as.numeric(data$year), formatC(data$monN, width=2, flag="0") ,"01", sep = "-"))
step 3: create a column EndDate as last day of the month based on startdate
data$EndDate <- data$StartDate
day(data$EndDate) <- days_in_month(data$EndDate)
step 4: apply answer from Apply seq.Date using two dataframe columns to create daily list for respective month
data$id <- c(1:nrow(data))
dataL <- setDT(data)[,list(datelist=seq(StartDate, EndDate, by='1 day'), costs= costs/days_in_month(EndDate)) , by = id]

MS Access 2010 (Design View): return Monday of the current week with Monday as 1st day of the week

I need to make my Access query always return the Monday of the current week. I have seen a few solutions on Google/StackOverflow but they are written in SQL and I am a beginner in creating Access queries (I am using the Design view to make them).
Goal: The week should be considered as M T W T F S S. Then, the query should always return the Monday of the current week. Therefore, if it is Sunday, it should still return the Monday before, NOT the next week's Monday. Can anyone explain how to do this using the Design View in Access 2010?
Keep in mind that in this context we are working with dates, so if we do Date() - 1, we will get 1 day prior to today.
Date() ~ Today's date
DatePart(
"w" - Weekday
Date() - Today's date
2 - vBMonday (Access assumes Sunday is the first day of the week, which is why this is necessary.)
1 - vbFirstJan1 - This gets into using the first week of the year. We could have omitted this, as 1 is the default.
)
-1 - Subtract 1 from the DatePart value.
Values
Date() = 4/27/2015 (at time of this writing)
DatePart("w",Date(),2,1) = 1
DatePart("w",Date(),2,1)-1 = 0
So we have Date()-0... Okay, what's so great about that? Well, let's look at a more useful scenario where today's date is a day other than Monday.
Let's act like today is 4/28/2015 (Tuesday)
Date() = 4/28/2015
DatePart("w",Date(),2,1) = 2
DatePart("w",Date(),2,1)-1 = 1
So, from the outside, in; give me the current weekday value. (1 = Monday, 2 = Tuesday, etc.), and subtract 1 from that -> that's how many days we need to subtract from the current date to get back to the weekday value of 1 (Monday).
Here's a function that will do this:
Public Function DatePrevWeekday( _
ByVal datDate As Date, _
Optional ByVal bytWeekday As VbDayOfWeek = vbMonday) _
As Date
' Returns the date of the previous weekday, as spelled in vbXxxxday, prior to datDate.
' 2000-09-06. Cactus Data ApS.
' No special error handling.
On Error Resume Next
DatePrevWeekday = DateAdd("d", 1 - Weekday(datDate, bytWeekday), datDate)
End Function
As vbMonday is 2 and your date is today, you can use the core expression in a query:
PreviousMonday: DateAdd("d",1-Weekday(Date(),2),Date())