-1

I want to be able to round of the current date to the nearest(later/equal to) half a year in the format DD MMM YYYY in python.

Example 1: If today is 10 Jul 2019, I want the output of my code to display 31 Dec 2019.

Example 2: If today is 15 Jan 2019, I want the output to be 30 Jun 2019.

Also, i want the months to be Jun/Dec (MMM), not 06 or 12.

I have imported the datetime package, but do not know how to go ahead. I am trying to use the round function, but not sure as well.

I have a code for my email: Please refer to the requirements for the half year ending DD MMM YYYY. i want the DD MMM YYYY to be autopopulated

2 Answers2

0

With help of this response Python round up integer to next hundred you could use something like this:

from datetime import datetime
from calendar import monthrange

def roundup(x, b=6):
    return x if x % b == 0 else x + b - x % b

def get_nearest_halfyear(date_str):
    d = datetime.strptime(date_str, '%d %b %Y')
    m = roundup(d.month)
    return datetime(year=d.year, month=m, day=monthrange(d.year, m)[-1] ).strftime('%d %b %Y')

for s in ['10 Jul 2019', '15 Jan 2019']:
    print('Please refer to the requirements for the half year ending {}.'.format(get_nearest_halfyear(s)))

Prints:

Please refer to the requirements for the half year ending 31 Dec 2019.
Please refer to the requirements for the half year ending 30 Jun 2019.
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

you can do this by checking whthr date.today().month//7 >0. this will give which half of the year current day falls in and return last day of the half year accordingly.

from datetime import datetime,date
def get_nearest_halfyear(date_var):
    return date(date_var.year, 12, 31).strftime("%d %b %Y") if date_var.month//7>0 else date(date_var.year, 6, 30).strftime("%d %b %Y")
print('Please refer to the requirements for the half year ending {}.'.format(get_nearest_halfyear(date.today())))

output : Please refer to the requirements for the half year ending 31 Dec 2019.

Shijith
  • 4,602
  • 2
  • 20
  • 34