Get First Date and Last Date of Current Quarter in Python

Get First Date and Last Date of Current Quarter in Python?

Any how i found some simple solution in c# and converted it into python,

from datetime import datetime,timedelta
current_date=datetime.now()
currQuarter = (current_date.month - 1) / 3 + 1
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = datetime(current_date.year, 3 * currQuarter + 1, 1) + timedelta(days=-1)

Python get first and last day of current calendar quarter

You can do it this way:

import bisect
import datetime as dt

def get_quarter_begin():
today = dt.date.today()

qbegins = [dt.date(today.year, month, 1) for month in (1,4,7,10)]

idx = bisect.bisect(qbegins, today)
return str(qbegins[idx-1])

This solves the "first" case; I'm leaving the "last" case as an exercise but I suggest keeping it as an independent function for clarity (with your original version it's pretty strange what happens if no arguments are passed!).

How to get quarter beginning date in python

You can convert to a period and then to a timestamp:

x = pd.to_datetime('2018-02-07')

res = x.to_period('Q').to_timestamp()

print(res)

Timestamp('2018-01-01 00:00:00')

Get start and end date of quarter from date and fiscal year end

You can define two function: one for the getting the quarter of a given date, and another for getting the start and end dates of a given quarter. To get the start and end dates of the previous quarter, you would just need to subtract one from the current quarter (with some handling of first quarter).

import datetime as dt
from dateutil import parser
from dateutil.relativedelta import relativedelta

def get_quarter(date):
"""
Returns the calendar quarter of `date`
"""
return 1+(date.month-1)//3

def quarter_start_end(quarter, year=None):
"""
Returns datetime.daet object for the start
and end dates of `quarter` for the input `year`
If `year` is none, it defaults to the current
year.
"""
if year is None:
year = dt.datetime.now().year
d = dt.date(year, 1+3*(quarter-1), 1)
return d, d+relativedelta(months=3, days=-1)

Once these are defined, we can define a simple function to get the previous quarter.

def prev_quarter_range(date):
"""
Returns the start and end dates of the previous quarter
before `date`.
"""
if isinstance(date, str):
date = parser.parse(date)
year = date.year
q = get_quarter(date)-1
# logic to handle the first quarter case
if q==0:
q = 4
year -= 1
return quarter_start_end(q, year)

And now you can assign the returned dates to variables

prev_q_start, prev_q_end = prev_quarter_range('2-feb-2011')

print(prev_q_start)
print(prev_q_end)

# prints:
2010-10-01
2010-12-31

Is there a function to determine which quarter of the year a date is in?

Given an instance x of datetime.date, (x.month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).


Originally two answers, multiply upvoted and even originally accepted (both currently deleted), were buggy -- not doing the -1 before the division, and dividing by 4 instead of 3. Since .month goes 1 to 12, it's easy to check for yourself what formula is right:

for m in range(1, 13):
print m//4 + 1,
print

gives 1 1 1 2 2 2 2 3 3 3 3 4 -- two four-month quarters and a single-month one (eep).

for m in range(1, 13):
print (m-1)//3 + 1,
print

gives 1 1 1 2 2 2 3 3 3 4 4 4 -- now doesn't this look vastly preferable to you?-)

This proves that the question is well warranted, I think;-).

I don't think the datetime module should necessarily have every possible useful calendric function, but I do know I maintain a (well-tested;-) datetools module for the use of my (and others') projects at work, which has many little functions to perform all of these calendric computations -- some are complex, some simple, but there's no reason to do the work over and over (even simple work) or risk bugs in such computations;-).

First and Last Date of Current and Previous Quarter For a Given Date in Scala

The following may do it. This is probably a UDF if it has to be applied to every row in the DF

import java.time.temporal.IsoFields
import java.time.temporal.IsoFields.QUARTER_OF_YEAR
import java.time.{LocalDate, YearMonth}

def printQuarterBeginAndEnd(localDate: LocalDate): Unit = {
val currentQuarter = localDate.get(QUARTER_OF_YEAR)
val currentYear = localDate.getYear
val currentMonth = localDate.getMonth
val startOfQuarter = YearMonth.of(currentYear, (currentQuarter-1) * 3 + 1).`with`(QUARTER_OF_YEAR, currentQuarter).atDay(1)
val endOfQuarter = YearMonth.of(currentYear, currentQuarter * 3).`with`(QUARTER_OF_YEAR, currentQuarter).atEndOfMonth()
println(s"Start $startOfQuarter ends $endOfQuarter")
}

printQuarterBeginAndEnd(LocalDate.now())
printQuarterBeginAndEnd(LocalDate.now().minus(1, IsoFields.QUARTER_YEARS))

Prints the following

import java.time.temporal.IsoFields
import java.time.temporal.IsoFields.QUARTER_OF_YEAR
import java.time.{LocalDate, YearMonth}

printQuarterBeginAndEnd: (localDate: java.time.LocalDate)Unit



Start 2022-01-01 ends 2022-03-31
Start 2021-10-01 ends 2021-12-31

scala> printQuarterBeginAndEnd(LocalDate.now().minus(1, IsoFields.QUARTER_YEARS)) Start 2021-10-01 ends 2021-12-31

scala> printQuarterBeginAndEnd(LocalDate.now()) Start 2022-01-01 ends 2022-03-31

scala> printQuarterBeginAndEnd(LocalDate.parse("2021-01-01")) Start 2021-01-01 ends 2021-03-31

How to find quarter first date and last date from current date using laravel

$date = CarbonImmutable::now();
$startCurrent = $date->startOfQuarter();
$startPrevious = $startCurrent->subQuarter();

echo $startPrevious . "\n";
echo $startPrevious->endOfQuarter() . "\n";
echo $startCurrent . "\n";
echo $startCurrent->endOfQuarter() . "\n";

Last day of quarter

Using a similar approach as in this answer:

df2 = df.withColumn(
'last_day',
F.expr("""
to_date(
date_trunc('quarter', to_date(input_date) + interval 3 months)
) - interval 1 day
""")
)

df2.show()
+----------+----------+
|input_date| last_day|
+----------+----------+
|2020-01-21|2020-03-31|
|2020-02-06|2020-03-31|
|2020-04-15|2020-06-30|
|2020-07-10|2020-09-30|
|2020-10-20|2020-12-31|
|2021-02-04|2021-03-31|
+----------+----------+

Then you can filter the rows where input_date == last_day


Edit: I might have misunderstood the question. You can try this approach using group by on the quarter and selecting the last row in each quarter:

from pyspark.sql import functions as F, Window

df2 = df.withColumn(
'rn',
F.row_number().over(Window.partitionBy(F.year('input_date'), F.quarter('input_date')).orderBy(F.desc('input_date')))
)

df2.show()
+----------+---+
|input_date| rn|
+----------+---+
|2021-02-04| 1|
|2020-10-20| 1|
|2020-07-10| 1|
|2020-02-06| 1|
|2020-01-21| 2|
|2020-04-15| 1|
+----------+---+

And filter the rows with rn = 1, which should be the last day in each quarter.



Related Topics



Leave a reply



Submit