如何在Python中获得一个月的第3个星期五?

时间:2015-02-23 18:36:45

标签: python python-2.7 date

我正试图从雅虎获取股票数据财务使用Python 2.7.9,但我只需要本月第3个星期五的数据。我有一个获取数据的功能,但需要一种方法来获取日期。我想要这样的东西:

def get_third_fris(how_many):
    # code and stuff
    return list_of_fris

因此,调用get_third_fris(6)将返回当前日期之后的6个项目长的第3个星期五列表。 日期必须是Unix时间戳。

(我对timedatetime几乎没有经验,所以请解释一下您的代码在做什么。)

谢谢!

12 个答案:

答案 0 :(得分:23)

您可以使用calendar模块列出周数,然后抓住该周的星期五。

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]

可以 格式化为Unix时间戳,但这并非易事。我会将您推荐给this excellent answer,根据您的日期是否为时区感知信息。

答案 1 :(得分:6)

您可以使用标准的python函数来查找本月的第三个星期五:

from datetime import timedelta, date
import calendar

def next_third_friday(d):
    """ Given a third friday find next third friday"""
    d += timedelta(weeks=4)
    return d if d.day >= 15 else d + timedelta(weeks=1)

def third_fridays(d, n):
    """Given a date, calculates n next third fridays"""

    # Find closest friday to 15th of month
    s = date(d.year, d.month, 15)
    result = [s + timedelta(days=(calendar.FRIDAY - s.weekday()) % 7)]

    # This month's third friday passed. Find next.
    if result[0] < d:
        result[0] = next_third_friday(result[0])

    for i in range(n - 1):
        result.append(next_third_friday(result[-1]))

    return result

我们可以应用上面的函数来获取下周五的时间戳:

import time

def timestamp(d):
    return int(time.mktime(d.timetuple()))

fridays = third_fridays(date.today(), 2)

print(fridays)
print(map(timestamp, fridays))

输出:

[datetime.date(2015, 3, 20), datetime.date(2015, 4, 17)]   
[1426802400, 1429218000]

答案 2 :(得分:4)

如何更简单的回答:

import calendar 
c = calendar.Calendar(firstweekday=calendar.SATURDAY)
monthcal = c.monthdatescalendar(my_year, my_month)
monthly_expire_date = monthcal[2][-1]

答案 3 :(得分:4)

假设您希望在每个第3个星期五进行一次活动,则可以使用熊猫(示例代码):

import pandas as pd

pd.date_range('2017-12-02','2020-08-31',freq='WOM-3FRI')

Output:
DatetimeIndex(['2017-12-15', '2018-01-19', '2018-02-16', '2018-03-16',
               '2018-04-20', '2018-05-18', '2018-06-15', '2018-07-20',
               '2018-08-17', '2018-09-21', '2018-10-19', '2018-11-16',
               '2018-12-21', '2019-01-18', '2019-02-15', '2019-03-15',
               '2019-04-19', '2019-05-17', '2019-06-21', '2019-07-19',
               '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15',
               '2019-12-20', '2020-01-17', '2020-02-21', '2020-03-20',
               '2020-04-17', '2020-05-15', '2020-06-19', '2020-07-17',
               '2020-08-21'],
              dtype='datetime64[ns]', freq='WOM-3FRI')

答案 4 :(得分:3)

我们不需要导入除datetime之外的任何内容。我们可以假设一周7天,工作日0 ==星期一。

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

答案 5 :(得分:2)

它易于使用dateutil来获得下一个星期五

import dateutil.parser as dparse
from datetime import timedelta
next_friday = dparse.parse("Friday")
one_week = timedelta(days=7)
friday_after_next = next_friday + one_week
last_friday = friday_after_next + one_week

这充分利用了星期五之间总有一周的事实......虽然我不确定这会回答你的问题,但它至少应该为你提供一个良好的起点

答案 6 :(得分:1)

使用dateutil.relativedelta

from dateutil.relativedelta import relativedelta, FR # $ pip install python-dateutil

def third_friday_dateutil(now):
    """the 3rd Friday of the month, not the 3rd Friday after today."""
    now = now.replace(day=1) # 1st day of the month
    now += relativedelta(weeks=2, weekday=FR)
    return now

或使用dateutil.rrule

from datetime import date, timedelta
from dateutil.rrule import rrule, MONTHLY, FR

def third_friday_rrule(now):
    return rrule(MONTHLY, count=1, byweekday=FR, bysetpos=3, dtstart=now.replace(day=1))[0]

def get_third_fris_rrule(how_many):
    return list(rrule(MONTHLY, count=how_many, byweekday=FR, bysetpos=3, dtstart=date.today()+timedelta(1)))

这是一个强力解决方案(快15倍):

#!/usr/bin/env python
import calendar
from datetime import date, timedelta
from itertools import islice

DAY = timedelta(1)
WEEK = 7*DAY

def fridays(now):
    while True:
        if now.weekday() == calendar.FRIDAY:
            while True:
                yield now
                now += WEEK
        now += DAY

def next_month(now):
    """Return the first date that is in the next month."""
    return (now.replace(day=15) + 20*DAY).replace(day=1)

def third_friday_brute_force(now):
    """the 3rd Friday of the month, not the 3rd Friday after today."""
    return next(islice(fridays(now.replace(day=1)), 2, 3))

def get_third_fris(how_many):
    result = []
    now = date.today()
    while len(result) < how_many:
        fr = third_friday_brute_force(now)
        if fr > now: # use only the 3rd Friday after today
            result.append(fr)
        now = next_month(now)
    return result

print(get_third_fris(6))

输出

[datetime.date(2015, 3, 20),
 datetime.date(2015, 4, 17),
 datetime.date(2015, 5, 15),
 datetime.date(2015, 6, 19),
 datetime.date(2015, 7, 17),
 datetime.date(2015, 8, 21)]

请参阅Converting datetime.date to UTC timestamp in Python

此处comparison with other solutions and tests (for all possible 400 years patterns)

答案 7 :(得分:0)

我概括了@pourhaus的答案以找到任何月份的第n天:

def nth_day_of_month(month, year, day_of_week, n):
    first_possible_day = {1: 1, 2: 8, 3: 15, 4: 22, 5: 29}[n]
    d = datetime.date(year, month, first_possible_day)
    w = d.weekday()
    if w != day_of_week:
        d = d.replace(day=(first_possible_day + (day_of_week - w) % 7))
    return d

答案 8 :(得分:0)

假设您使用熊猫:

def exp_friday(df):
mask = np.where((df.index.day > 14) & 
                (df.index.day < 22) & 
                (df.index.dayofweek == 4), True, False)
return df[mask]

答案 9 :(得分:0)

这是一个通用功能,可以以列表形式为您提供特定星期的所有日期。

def frecuencia_daymng(self, start_day, year, month, dayofweek):
    """dayofweek starts on MONDAY in 0 index"""
    c = calendar.Calendar(firstweekday=start_day)
    monthcal = c.monthdatescalendar(year, month)
    ldates = []
    for tdate in monthcal:
        if tdate[dayofweek].month == month:
            ldates.append(tdate[dayofweek])
    return ldates

假设您要在2020年10月的所有星期一。

frecuencia_daymng(calendar.MONDAY, 2020, 10, 0)

这将为您提供输出。

[datetime.date(2020, 10, 5),
 datetime.date(2020, 10, 12),
 datetime.date(2020, 10, 19),
 datetime.date(2020, 10, 26)]

所以现在您有一个月的第一个,第二个……星期一。

答案 10 :(得分:0)

我的建议是从每月的第一天开始,然后找到最近的星期五。

4 表示为来自 datetime.weekday() 方法的星期五。

所以我们然后从 4(Friday) 中减去一个月第一天的工作日 如果结果是否定的,则找到的最近的星期五是上个月,所以我们添加 7 天,否则我们已经有了第一个星期五。

那么结果就像再添加 14 天以获得第三个星期五一样简单,然后将代表第三个星期五的 timedelta 添加到该月的第一天。

from datetime import datetime, timedelta

def get_third_friday(year, month):
    first_day_of_month = datetime(year, month, 1)
    closest_friday = 4 - first_day_of_month.weekday()
    if closest_friday < 0:
        first_friday = closest_friday + 7
    else:
        first_friday = closest_friday

    third_friday = first_friday + 14
    return first_day_of_month + timedelta(third_friday)

答案 11 :(得分:-1)

from dateutil.relativedelta import *
from datetime import *

def find_mth_friday(your_date,m):
    mth_friday = your_date + relativedelta(day=1, weekday=FR(m)) #sets day=1 in your_date and adds m fridays to it.
    mth_friday_timestamp = int(mth_friday.strftime("%s")) #converting datetime to unix timestamp
    return mth_friday_timestamp

def get_third_fris(n):
    output_timestamps = []
    today = datetime.now() #gets current system date
    for i in range(1,n+1): #value of i varies from 1 to 6 if n=6
        next_month = today + relativedelta(months=+i) #adds i months to current system date
        third_friday = find_mth_friday(next_month,3) #finds third friday of the month using 'find_mth_friday()', the function we defined
        output_timestamps.append(third_friday)
    return output_timestamps

print(get_third_fris(6)) #let's try invoking our function with n=6 dates

这是您想要的吗?