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

spe*_*ekr 10 python date python-2.7

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

def get_third_fris(how_many):
    # code and stuff
    return list_of_fris
Run Code Online (Sandbox Code Playgroud)

因此,该呼叫get_third_fris(6)将在当前日期之后返回6个项目长的第3个星期五列表.日期需要是Unix时间戳.

(我有几乎没有经验time或者datetime,请解释一下你的代码做什么.)

谢谢!

Ada*_*ith 25

您可以使用该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]
Run Code Online (Sandbox Code Playgroud)

可以格式化为Unix时间戳,但这并非易事.我会向您推荐这个优秀的答案,其中包含的信息取决于您的日期是否符合时区意识.

  • 它现在有效.虽然[@ JuniorCompressor的解决方案速度提高了9倍](https://gist.github.com/zed/11441b4776f7bbecc830) (3认同)
  • 非常聪明:P)你赢了:P (2认同)
  • 第三周的星期五不一定是第三个星期五! (2认同)
  • @spelchekr:这个答案对于“年,月= 2015, 8”来说是不正确的——它返回“2015-08-14”,但应该是“2015-08-21”。 (2认同)

pou*_*aus 13

我们不需要导入除日期时间以外的任何内容。我们可以假设一周有 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
Run Code Online (Sandbox Code Playgroud)


小智 8

假设你想要一个每第三个星期五的范围,你可以只使用熊猫,示例代码:

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')
Run Code Online (Sandbox Code Playgroud)


Jun*_*sor 7

您可以使用标准的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
Run Code Online (Sandbox Code Playgroud)

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

import time

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

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

print(fridays)
print(map(timestamp, fridays))
Run Code Online (Sandbox Code Playgroud)

输出:

[datetime.date(2015, 3, 20), datetime.date(2015, 4, 17)]   
[1426802400, 1429218000]
Run Code Online (Sandbox Code Playgroud)


roc*_*man 5

一个更直接的答案如何:

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


Jor*_*ley 3

使用 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
Run Code Online (Sandbox Code Playgroud)

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