Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python-2.7

How can i get the Current Quarter year and then First Date and last Date of Current Quarter Year in Python?

i want by importing datetime

import datetime

People look into Stack overflow need straight forward answer and which should be very simple. Which ever link you provided it having lot of Comments. SO, users has to go through all the comments to find correct answer. I am writing simple and straight forward answer.

like image 859
Krishh Avatar asked May 10 '16 10:05

Krishh


People also ask

How do I extract a date from a quarter in Python?

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;-).

How do I find the start date and end date in python?

You can use datetime. timedelta for that.


1 Answers

I believe that none of the current answers are still valid in Python 3, so since this is the top hit in google for first and last day of quarter, I will provide a solution that works in Python 3 (mostly Ahmet's with // instead of /):

from datetime import date as date_class
from datetime import timedelta, datetime


def get_quarter(p_date: date_class) -> int:
    return (p_date.month - 1) // 3 + 1


def get_first_day_of_the_quarter(p_date: date_class):
    return datetime(p_date.year, 3 * ((p_date.month - 1) // 3) + 1, 1)


def get_last_day_of_the_quarter(p_date: date_class):
    quarter = get_quarter(p_date)
    return datetime(p_date.year + 3 * quarter // 12, 3 * quarter % 12 + 1, 1) + timedelta(days=-1)


assert get_quarter(datetime(year=2021, month=10, day=5).date()) == 4
assert get_quarter(datetime(year=2020, month=9, day=25).date()) == 3
assert get_quarter(datetime(year=2020, month=12, day=11).date()) == 4
assert get_quarter(datetime(year=2020, month=1, day=2).date()) == 1

assert get_first_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 7, 1)
assert get_first_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 1, 1)

assert get_last_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 9, 30)
assert get_last_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 3, 31)
assert get_last_day_of_the_quarter(datetime(2020, 5, 6).date()) == datetime(2020, 6, 30)
like image 72
Peter Avatar answered Sep 23 '22 20:09

Peter