How can I get the 3rd Friday of a month in Python?

date, python, python-2.7

Solution

You can use the `calendar` module to list weeks, then grab the Friday of that week.

import calendar

c = calendar.Calendar(firstweekday=calendar.SUNDAY)

year = 2015; month = 2

monthcal = c.monthdatescalendar(year,month)
third_friday = [day for week in monthcal for day in week if \
                day.weekday() == calendar.FRIDAY and \
                day.month == month][2]

You can format to Unix timestamp, but it's non-trivial. I'll refer you to this excellent answer which has info based on whether or not your date is timezone-aware.

Problem

I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this: ``` def get_third_fris(how_many): # code and stuff return list_of_fris ``` So that calling `get_third_fris(6)` will return a 6-item-long list of 3rd Fridays following the current date. The dates need to be Unix timestamps. (I have pretty much no experience with `time` or `datetime`, so please explain what your code is doing.) Thanks!

Original source

Related problems