I'd like to create a function to take the current month number (1 to 12) and produce a fiscal quarter i.e. 1, 2, 3 or 4.
A lot of the examples I have found use case statements but this seems over engineered for what I feel should be achievable using math.
I have tried a few different methods but have fallen a little short such as:
function getQuarter(m) { return round(m/4) }
Edit: building on #neil answer the function can be further shortened to:
function getQuarter(m) { return Math.ceil(m/3) }
function getQuarter(m) { return Math.floor((m - 1)/3) + 1 }
You subtract 1, because January isn't 1 month into the new year, it's the first month. Likewise 12 isn't a new quarter, it's the last month of the last quarter.
Divide by 3 instead of 4 (3 months to a quarter) and floor it. Then add one and the returned value is a number from 1 to 4 indicating which quarter you're in.
Good luck!
Related
Good morning to all,
I would need your help of the most professional!
In my datastudio I have a column MONTH and I would like to create an automatism, where I can take the column MONTH -1 and based on the previous month, and once done this take into account the column RATING and return the value.
I used this formula but it doesn’t work:
WHEN Month < DATETIME_TRUNC(TODAY(), MONTH) AND Month >= DATETIME_TRUNC(DATETIME_SUB(TODAY(), INTERVAL 1 MONTH), MONTH) THEN 1 "
can you help me?
I would like to take the case Month and then take into account the previous Month and on this basis calculate the rating
I have a couples of weeknumbers of interest. Lets take '202124' (this week) as an example. How can I subtract x weeks from this week number?
Lets say I want to know the week number of 2 weeks prior, ideally I would like to do 202124 - 2 which would give me 202122. This is fine for most of the year however 202101 - 2 will give 202099 which is obviously not a valid week number. This would happen on a large scale so a more elegant solution is required. How could I go about this?
convert the year week values to dates subtract in days and format the output.
x <- c('202124', '202101')
format(as.Date(paste0(x, 1), '%Y%W%u') - 14, '%Y%V')
#[1] "202122" "202052"
To convert year week value to date we also need day of the week, I have used it as 1st day of the week.
I am needing to count month between collect dates. I need to know if the test was run in the last 3 months. Below is the code I used but it is giving me a count of zero, but I know they had 3 of the same tests run in a year because I can see the dates. I understand the first one have a count of zero, because there is no test before that, but the count for the other should be 3, 5 respectively.
DATEDIFF('month',[Collect Date],[Collect Date])
Dates of the Tests.
1/8/2015
4/23/2015
9/30/2015
What you are looking for is possible using the LOOKUP function in Tableau. Keep in mind, that the result relies heavily on the data that is displayed and how it is displayed (sorted, etc).
You can create a calculated field like this:
DATEDIFF("month",LOOKUP(ATTR([Test Date]),-1),ATTR([Test Date]))
Which calculates the number of months between the date in the current row and the date from the prior row.
Your result will look something like this:
I have a dataset with locations and dates. I would like to calculate week of the year as number (00–53) but using Thursday as the first day of the week. The data looks like this:
location <- c(a,b,a,b,a,b)
date <- c("04-01-2013","26-01-2013","03-02-2013","09-02-2013","20-02-2013","03-03-2013")
mydf <- data.frame(location, date)
mydf
I know that there is strftime function for calculating week of year but it is only possible to use Monday or Sunday as the first day of the week.
Any help would be highly appreciated.
Just add 4 to the Date-formatted values:
> mydf$Dt <- as.Date(mydf$date, format="%d-%m-%Y")
> weeknum <- as.numeric( format(mydf$Dt+3, "%U"))
> weeknum
[1] 1 4 5 6 7 9
This uses a 0 based counting convention since that is what strftime provides and we are just piggybacking off that code base, so the first Friday in a year that begins on Tuesday as was the case in 2013 would be a 1-week result. Add 1 to the value if you want a 1 based convention. (Fundamentally, Date-formated values are in an integer sequence from the "origin" so they don't really recognize years or weeks. Adding 4 just shifts the reference frame of the underlying Date-integer.)
Edit note. Changed to an add three strategy per Gabor's advice. .... which still does not address the question of how to deal with the last week of the prior year.
Since the question stated that week goes from 00-53 we assume that the week number is the number of Thursdays in the year on or before the date in question. Thus, the first Thursday in the year begins week 1 and week 0 is assigned to any days prior to that.
(There were comments that if the first day of the year were Tuesday then that would be week 1 but if that were the case there could never be a week 0 as seems to be required in the subject so some clarification on precisely what the definition of week number is may be required. Here we are going to use the definition in the preceding paragraph but it would not be hard to change it if we knew what the definition was. For example, if we always wanted the first week in the year to be 1 even if it were a short week then we could add !is.thu(jan1(d)) to the result.)
Both of the solutions below are short enough that they could be expressed in one statement; however, we have factored them into several short functions each for clarity. The first is particularly straight forward but the second is automatically vectorized without the need for a sapply and would likely be more efficient.
1. sum Thursdays in year This solution assumes the input d is of class "Date" and just sums the number of Thursdays in the year before or on it:
is.thu <- function(x) weekdays(x) == "Thursday"
jan1 <- function(x) as.Date(cut(x, "year"))
week4 <- function(d) {
sapply(d, function(d) sum(is.thu(seq(jan1(d), d, by = "day"))))
}
We can test it like this:
d <- as.Date(c("2013-01-04", "2013-01-26", "2013-02-03", "2013-02-09",
"2013-02-20", "2013-03-03"))
week4(d) # 1 4 5 6 7 9
2. nextthu
Based on the nextfri function in the zoo quickref vignette we see that the number of days since the Epoch (1970-01-01) of the next Thursday (or the day in question if its already a Thursday) is as given by nextthu in the first line below. Applying this to the first day of the year we derive the result where d is as before:
nextthu <- function(d) 7 * ceiling(as.numeric(d) / 7)
week4a <- function(d) (as.numeric(d) - nextthu(jan1(d))) %/% 7 + 1
and here is a test
week4a(d) # 1 4 5 6 7 9
ADDED: fixed bug in second solution.
I have seen a lot of info on how to subtract one datetime from the other and how to add years on to a datetime. but the following is giving me a headache....
When a user inserts a record a hidden field called subdate with a value of datetime.now is added to the db.
I then need to have an 'old records' page that lists all the entries that are over 1 year old and was hoping to use something (but using subtract method) similar to;
(DateTime.Now.AddYears(1))
but there is no SubtractYears available? Why?
Please can you let me know how I achieve the same result?
DateTime.Now.AddYears(-1)
From the documentation:
A number of years. The value parameter can be negative or positive.
now = datetime.now()
last_year = (now.year - 1)
datestr = (datetime.strptime(str(now.year - 1), "%Y")).strftime("%y")
print(f"Last Year: {datestr}")
The output will be:
Last Year: 20
If you prefer to have four digit year then change %y to %Y