Skip to content Skip to sidebar Skip to footer

Print Date Of Last Tuesday Of Each Month Of Next Year Using Python

How can I print the date of the last Tuesday of each month for next year using Python. For example the first line outputted would be: 30/Jan/2018 I do not want to have the full nam

Solution 1:

The calendar module is perfect for this:

You can use calendar.month_abbr which is an array of abbreviated months just like you want.

week is an array representing the days of the week starting at Monday so Tuesday would be week[1].

import calendar
import datetime

now = datetime.datetime.now()
next_year = now.year + 1for month inrange(1, 13):
    last_tuesday = max(week[1] for week in calendar.monthcalendar(next_year, month))
    print('{}/{}/{}'.format(last_tuesday, calendar.month_abbr[month], next_year))

Output:

30/Jan/201827/Feb/201827/Mar/201824/Apr/201829/May/201826/Jun/201831/Jul/201828/Aug/201825/Sep/201830/Oct/201827/Nov/201825/Dec/2018

Solution 2:

I would also suggest the pandas DateOffset object LastWeekOfMonth.

Describes monthly dates in last week of month like "the last Tuesday of each month"

from pandas.tseries.offsets import LastWeekOfMonth

def last_tues(year):
    return (pd.date_range('1/1/' + str(year), periods=12, freq='M')
           - LastWeekOfMonth(n=1, weekday=1)).strftime('%d/%b/%Y'))

last_tues(2018)
Out[31]: 
array(['30/Jan/2018', '27/Feb/2018', '27/Mar/2018', '24/Apr/2018',
       '29/May/2018', '26/Jun/2018', '26/Jun/2018', '28/Aug/2018',
       '25/Sep/2018', '30/Oct/2018', '27/Nov/2018', '25/Dec/2018'], 
      dtype='<U11')

Post a Comment for "Print Date Of Last Tuesday Of Each Month Of Next Year Using Python"