Python:一个月的第三个星期五 [英] Python: third Friday of a month

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

问题描述

我是一名菜鸟python程序员,我需要编写脚本来检查给定的日期(以 Month,day year的形式作为字符串传递)是否是该月的第三个星期五。我正在使用Python 2.7。

I am a rookie python programmer and I need to write a script to check if a given date (passed as a string in the form 'Month, day year') is the third Friday of the month. I am using Python 2.7.

例如,这些日期可以帮助您更好地理解我的问题。每年都有日历。

For example, these dates can help you better understand my problem. Have a yearly calendar at hand.


  • 输入--->输出

  • '2013年1月18日'--->正确

  • '2013年2月22日'--->错误

  • '6月21日,2013'---> True

  • '2013年9月20日'---> True

  • input ---> output
  • 'Jan 18, 2013' ---> True
  • 'Feb 22, 2013' ---> False
  • 'Jun 21, 2013' ---> True
  • 'Sep 20, 2013' ---> True

我只想使用该语言提供的标准类,例如时间,日期时间,日历等。

I just want to use standard classes provided by the language, like time, datetime, calendar, etc.

我调查了一些答案,但看到的计算像每天添加/减去86400秒,甚至根据一个月的天数进行比较。恕我直言,这些都是错误的,因为Python中的自由已经处理了这些细节,因此无需重新发明轮子。日历和日期也很复杂:leap年,leap秒,时区,星期数等,因此我认为最好让图书馆解决这些棘手的细节。

I have looked into some answers but I see calculations like addidng/substracting 86400 seconds for every day or even doing comparisons depending on the number of days that a month has. IMHO these are wrong because the libreries in Python already take care of these details so there is no need to reinvent the wheel. Also calendars and dates are complex: leap years, leap seconds, time zones, week numbers, etc. so I think is better to let the libraries solve these tricky details.

预先感谢您的帮助。

推荐答案

应该这样做:

from datetime import datetime 

def is_third_friday(s):
    d = datetime.strptime(s, '%b %d, %Y')
    return d.weekday() == 4 and 15 <= d.day <= 21

测试:

print is_third_friday('Jan 18, 2013')  # True
print is_third_friday('Feb 22, 2013')  # False
print is_third_friday('Jun 21, 2013')  # True
print is_third_friday('Sep 20, 2013')  # True

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

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