如何在Python中获得一个月的第三个星期五? [英] How can I get the 3rd Friday of a month in Python?

查看:4189
本文介绍了如何在Python中获得一个月的第三个星期五?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python 2.7.9从Yahoo! Finance获取股票数据,但我只需要本月第3个星期五的数据。我有一个函数来获取数据,但需要一种方法来获取日期。我想要这样的东西:

  def get_third_fris(how_many):
#代码和东西
return list_of_fris

所以调用 get_third_fris(6)将返回当前日期之后的第三个星期五的6个项目长的列表。 日期需要是Unix时间戳。



(我几乎没有经验与时间 datetime ,所以请解释你的代码正在做什么。)



谢谢!

解决方案

您可以使用 日历 模块列出周,然后抓住那周的星期五。

  import calendar 

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

year = 2015; month = 2

monthcal = c.monthdatescalendar(年,月)
third_friday = [如果\
day.weekday()= = calendar.FRIDAY和\ $​​ b $ b day.month == month] [2]

您可以 格式化为Unix时间戳,但它不是微不足道的。我会将您转到这个非常好的答案,该信息是基于您的日期是否具有时区感知信息。 p>

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!

解决方案

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.

这篇关于如何在Python中获得一个月的第三个星期五?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆