Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 654
spelchekr Avatar asked Feb 23 '15 18:02

spelchekr


People also ask

How do you get Friday in Python?

Friday is always 4 when using the weekday() method. The isoweekday() method gives Friday as 5, because it treats Monday through Sunday as 1 through 7. You can use calendar.

How do you get the first Monday of the month in Python?

A slightly different method – The date. weekday() function gives your an index of the day of the week (where Monday is 0 and Sunday is 6). You can use this value to directly calculate the which date any day of the week will fall on.


2 Answers

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.

like image 89
Adam Smith Avatar answered Oct 07 '22 14:10

Adam Smith


We do not need to import anything other than datetime. We can assume 7 days in a week and weekday 0 == Monday.

import datetime

def third_friday(year, month):
    """Return datetime.date for monthly option expiration given year and
    month
    """
    # The 15th is the lowest third day in the month
    third = datetime.date(year, month, 15)
    # What day of the week is the 15th?
    w = third.weekday()
    # Friday is weekday 4
    if w != 4:
        # Replace just the day (of month)
        third = third.replace(day=(15 + (4 - w) % 7))
    return third
like image 27
pourhaus Avatar answered Oct 07 '22 14:10

pourhaus