24
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

datetimeで曜日を調べる

Last updated at Posted at 2016-07-31

pythonのdatetimeモジュールで曜日を調べるにはweekdayメソッドを使うといい。
weekdayメソッドはオブジェクトが作る日付の曜日を0-6の数字で返してくれる。
0が月曜日、1が火曜日で6が日曜日なので月〜日を格納したリストを用意しておけば曜日に変換できる。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from datetime import *
from time import *

print "以下の形式で日付を入力してください 例:'2016/07/30'."
user_input_date = raw_input("日付:")
yobi = ["","","","","","",""]
while user_input_date != "bye":
    try:
        a = datetime.strptime(user_input_data,'%Y/%m/%d')
        print "{}は{}曜日です".format(user_input_date,yobi[a.weekday()])
    except ValueError:
        print "誤った日付です"
    user_input_date = raw_input("your date :")
else:
    sys.exit(1)

python3.xで書くとこんな感じ。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from datetime import *
from time import *

print ("日付を入力してください '2016/07/30'.")
user_input_date = input("your date :")

yobi = ["","","","","","",""]

while user_input_date != "bye":
    try:
        a = datetime.strptime(user_input_date,'%Y/%m/%d')
        print ("{}は{}曜日です".format(user_input_date,yobi[a.weekday()]))
    except ValueError:
        print ("誤った日付です")
    user_input_date = input("your date :")
else:
    sys.exit(1)
24
22
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?