17

私は初心者の python プログラマーであり、特定の日付 (「Month, day year」の形式で文字列として渡される) がその月の第 3 金曜日であるかどうかを確認するスクリプトを作成する必要があります。Python 2.7 を使用しています。

たとえば、これらの日付は、私の問題をよりよく理解するのに役立ちます。年間カレンダーをお手元にご用意ください。

  • 入力 ---> 出力
  • 「2013 年 1 月 18 日」 ---> True
  • 「2013 年 2 月 22 日」 ---> False
  • 「2013 年 6 月 21 日」 ---> True
  • 「2013 年 9 月 20 日」 ---> True

時間、日時、カレンダーなど、言語によって提供される標準クラスを使用したいだけです。

いくつかの回答を調べましたが、毎日 86400 秒を加算/減算したり、月の日数に応じて比較を行ったりするなどの計算が表示されます。Pythonのライブラリはすでにこれらの詳細を処理しているため、ホイールを再発明する必要がないため、これらは間違っています。また、カレンダーと日付は複雑です: 閏年、閏秒、タイムゾーン、週番号など.

よろしくお願いします。

4

5 に答える 5

36

これはそれを行う必要があります:

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
于 2013-08-25T00:38:51.363 に答える
2

これを達成するさらに別の方法...整数除算を使用...

import datetime

def is_date_the_nth_friday_of_month(nth, date=None):
    #nth is an integer representing the nth weekday of the month
    #date is a datetime.datetime object, which you can create by doing datetime.datetime(2016,1,11) for January 11th, 2016

    if not date:
        #if date is None, then use today as the date
        date = datetime.datetime.today()

    if date.weekday() == 4:
        #if the weekday of date is Friday, then see if it is the nth Friday
        if (date.day - 1) // 7 == (nth - 1):
            #We use integer division to determine the nth Friday
            #if this integer division == 0, then date is the first Friday, 
            # if the integer division is...
            #   1 == 2nd Friday
            #   2 == 3rd Friday
            #   3 == 4th Friday
            #   4 == 5th Friday
            return True

    return False
于 2016-01-29T22:39:32.593 に答える