3

Is there a sleekest way to calculate the quarter for today's date? I know there are bunch of solutions over here but I am looking for something slick which doesn't need any other library that datetime.

I am currently calculating week by using the following code which gives me output for week: 2017-26

import datetime as DT

varWeek = (str(DT.date.today().isocalendar()[0]) + "-" + 
           str(DT.date.today().isocalendar()[1]))

I need a quarter for today's date in the following format.

'2017-Q2'.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
nomad
  • 973
  • 2
  • 9
  • 22
  • 2
    Possible duplicate of [Is there a Python function to determine which quarter of the year a date is in?](https://stackoverflow.com/questions/1406131/is-there-a-python-function-to-determine-which-quarter-of-the-year-a-date-is-in) – Michal K Jun 29 '17 at 21:38

1 Answers1

4
def quarter(date):
    return '{}-Q{}'.format(date.year, (date.month - 1) // 3 + 1)

or

def quarter(date):
    a, b = divmod(date.month, 3)
    return '{}-Q{}'.format(date.year, a + bool(b))

Test it:

>>> quarter(datetime.date.today())
'2017-Q2'
Mike Müller
  • 82,630
  • 20
  • 166
  • 161