问题
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 name of the month only the first 3 characters!
Currently I have figured out how to get the next year:
import datetime
now = datetime.datetime.now()
next_year = now.year + 1
Can anyone please help?
回答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 + 1
for month in range(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/2018
27/Feb/2018
27/Mar/2018
24/Apr/2018
29/May/2018
26/Jun/2018
31/Jul/2018
28/Aug/2018
25/Sep/2018
30/Oct/2018
27/Nov/2018
25/Dec/2018
回答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')
来源:https://stackoverflow.com/questions/44305610/print-date-of-last-tuesday-of-each-month-of-next-year-using-python