How can I in rails calculate the number of weeks in a given month?
Thanks
i dont know exactly what you want... But maybe you want something like this:
(Time::days_in_month(05,2010).to_f / 7)
#> 4.42857142857143
I needed to know how many weeks including partial weeks there were in a month. Think of it like rows in a calendar. How many rows do you need? You have to consider the number of days and also what day the month starts on. October 2011 actually has 6 unique weeks for example.
This is my answer (#date is the current date):
#week_count = (0.5 + (#date.at_end_of_month.day + #date.at_beginning_of_month.wday).to_f / 7.0).round
You can use the following methods:
WEEK_NUMBER_FORMAT = '%W'
# Returns the first day of month.
# If invoked without any arguments, this would return the
# first day of current month
def first_day_of_month(date_time=Time.now)
date_time.beginning_of_month
end
# Returns the last day of month.
# If invoked without any arguments, this would return the
# last day of current month
def last_day_of_month(date_time=Time.now)
date_time.end_of_month
end
# Returns the week number in the year in which the specified date_time lies.
# If invoked without any arguments, this would return the
# the week number in the current year
def week_number(date_time=Time.now)
date_time.strftime(WEEK_NUMBER_FORMAT).to_i
end
# Returns the number of weeks in the month in which the specified date_time lies.
# If invoked without any arguments, this would return the
# the number of weeks in the current month
def weeks_in_month(date_time=Time.now)
week_number(last_day_of_month(date_time)) - week_number(first_day_of_month(date_time)) + 1
end
Usage: weeks_in_month(date_time)
Hope it helps:
Thanks,
Jignesh
def number_of_weeks_in_month
4
end
Use the gem week_of_month
d = Date.new(2012,1,1)
d.total_weeks
=> 5
def number_of_weeks_month(start_of_month, count, end_of_month)
if start_date > end_of_month
return count
else
number_of_weeks_month(start_date.end_of_week + 1, count + 1, end_of_month)
end
end
get number of weeks for month like this
number_of_weeks_month(Date.parse("2017-11-01"),0,Date.parse("2017-11-30"))
this return 4
Date.today.end_of_month.day/7
=> 4
Related
!Get the week start date and week end date from week number in raw query #2 after group all ids in array
$test=DB::table('bookings')
->select([
'bookings.organization_id',
DB::raw('week(bookings.created_at) as week'), // this give me week number I need start date and end date starting date Sunday and end date Saturday
DB::raw('year(created_at) as year'),
the second after group by organization_id I need all booking id in array not string
// I try this but give like this "1,4,6,7,9" I need ["1","4","6","7","9"]
DB::raw('group_concat(bookings.id) as bookings_id'),
To get the start and end of week you can use this:
$test=DB::table('bookings')
->select([
'bookings.organization_id',
DB::raw('DATE(bookings.created_at + INTERVAL (1 - DAYOFWEEK(bookings.created_at)) DAY) as start_date'),
DB::raw('DATE(bookings.created_at + INTERVAL (7 - DAYOFWEEK(bookings.created_at)) DAY) as end_date')
])
->get();
And for second question:
MySQL does not have concept of array type for data.
You need to explode the data into an array, using php code like this:
$bookingsIds = explode(',', $test->bookings_id);
I have a dataframe with a datetime64 column called DT. Is it possible to use groupby to group by financial year from April 1 to March 31?
For example,
Date | PE_LOW
2010-04-01 | 15.44
...
2011-03-31 | 16.8
2011-04-02 | 17.
...
2012-03-31 | 17.4
For the above data, I want to group by Fiscal Year 2010-2011 and Fiscal Year 2011-2012 without creating an extra column.*
The first thing you want to do is define a function that outputs the financial year as a value. You could use the following.
def getFiscalYear(dt):
year = dt.year
if dt.month<4: year -= 1
return year
You say you don't want to use an extra column to group the frame. Typically the groupby method is called by saying something like this df.groupby("colname") however that statement is semantically equivalent to df.groupby(df["colname"] - meaning you can do something like this...
grouped = DT.groupby(DT['Date'].apply(getFiscalYear))
and then apply a method to the groups or whatever you want to do. If you just want these groups separated call grouped.groups
With pandas.DatetimeIndex, that is very simple:
DT.groupby(pd.DatetimeIndex(DT.Date).shift(-3,freq='m').year)
Or if you use Date as an index of DT, it is even simpler:
DT.groupby(DT.index.shift(-3,freq='m').year)
But beware that shift(-3,freq='m') shifts date to ends of months; for example, 8 Apr to 31 Jan and so on. Anyway, it fits your problem well.
I had a similar problem and used the following to offset the business year end to March (month=3) using Grouper and specifying the frequency:
grouped_df = df.groupby([pd.Grouper(key='DateColumn', freq=pd.tseries.offsets.BYearEnd(month=3))])
Pandas Business Year End and
Grouper
The simplest method I've found for this (similar to Alex's answer, but slightly more concise):
df.groupby([pd.Grouper(key='DateColumn', freq="A-MAR")])
If you want year finishing on the last working day you can use freq="BA-MAR"
Similar to this answer, but I would (at this time of this initial post) need to report that the fiscal year is 2023. This is acheived by reversing the inequality and changing the decrement to an increment.
def fiscal_year(dt):
year = dt.year
if dt.month > 4:
year += 1
return year
I am new to T-SQL and needed urgent assistance here.
I am trying to get the week number from a given date.
I understand that there is a build in function for it but the value return is not exactly what I wanted.
For e.g., by using select datepart(wk, '2013-01-07'), it would return me '2'.. but the actually fact is it should return '1' instead of '2'.
Any ideas how to correct this issue?
You can use dy datepart specifier to get dayOfYear number and divide it by 7:
select (datepart(dy, '2013-01-05') - 1) / 7 + 1;
Working DEMO.
Try this
SELECT DATEPART(WEEK,GETDATE())
This depends on hop you define the first week. Does it always start on the same weekday? or does it always start on the first of January? If you want it to always start on the same weekday, then use Set datefirst to tell T-SQL what weekdaty you want to define as the start of the week. If you want it to always start on Jan 1, then just use day of year instead of week, subtract 1, integer divide by 7 and add 1.
declare #dat DateTime = getdate()
Select Select (datepart(dy, #dat)-1) / 7 + 1
Although going from memory, I believe the ISO standard for the first week of the year is the week in the year that the first Thursday of the year is in. This would possibly explain why the built in function gives a result different to that you require.
I have salesdate for whole last year (01/01/2012 to 12/31/2012). I want to create
a week variable in such a way that there are only 4 weeks consistent over the months.
In other words, I want
01/01/2012-01/07/2012 = week1
01/08/2012-01/14/2012 = week2
01/15/2012-01/21/2012 = week3
01/22/2012-01/31/2012 = week4
(I can not use ww. format because my week 4 does not fit the always definition of week 4 in Oracle SQL Developer.)
I am wondering if anybody can help me on this.
Try this expression:
select LEAST(TRUNC((EXTRACT(day FROM salesdate) + 6) / 7), 4) week
FROM salesdata;
Note:
EXTRACT extracts the day from the date
TRUNC( (x + 6) / 7) divides it by seven days and truncates it to an integer number
LEAST( x, 4 ) limits it to a maximum of 4
Well your last week has 9 days, so that is kind of weird...
but you could try something like:
CREATE OR REPLACE FUNCTION GET_WEIRD_WEEK(I_DATE DATE)
RETURN NUMBER AS
BEGIN
RETURN CASE
WHEN FLOOR(TO_CHAR(I_DATE,'DD')/7)+1 > 3
THEN 4
ELSE FLOOR(TO_CHAR(I_DATE,'DD')/7)+1
END;
END;
otherwise i would suggest you distribute the days evenly across the month's quarters:
CREATE OR REPLACE FUNCTION GET_WEIRD_WEEK(I_DATE DATE) RETURN NUMBER AS
BEGIN
RETURN FLOOR(TO_CHAR(I_DATE,'DD')/TO_CHAR(LAST_DAY(I_DATE),'DD')*4)+1;
END;
I have an app that tracks employee times. Employees are required to have at least 2 days off every 12 days... An employee should enter a record with boolean true for day_off...but, in case they don't I also want to find breaks in days that could also days off. I am trying to simply count records whos date decrements by one day, starting from the boolean day_off Or break in consecutive dates...and ending on a given date.
This is the helper I am working on
def consecutive_days_on(user, dutylog)
# dutylog will be supplied via a loop
last_day_off = user.dutylogs.where("entry_date < ?", dutylog.entry_date).where(day_off: true).last
start_date = dutylog.entry_date
if last_day_off.present?
end_date = last_day_off.entry_date
# if the user logged their days off
else
end_date = user.dutylogs.where("entry_date < ?", dutylog.entry_date).last.entry_date
# as of now this just finds the last record...it needs to iterate and increment date to find a break in days on
# to find break in consecutive dates...if user did not log days off
end
user.dutylogs.where("entry_date >= ? AND entry_date <= ?", start_date, end_date).count
# count the records between the two dates...to find consecutive days on
end
I refactored my helper...and it works. I decided to rely on the user entering a day as off in their log...and not assuming that a break in entered days could be considered a day off.
def consecutive_days_on(user, dutylog)
last_day_off = user.dutylogs.where(day_off: true).where("entry_date < ?", dutylog.entry_date).select(:entry_date).last
start_date = dutylog.entry_date
if last_day_off.present?
end_date = last_day_off.entry_date
else
end_date = dutylog.entry_date
end
a = user.dutylogs.where("entry_date >= ? AND entry_date <= ?", end_date, start_date).count
a-1
end