Help us understand the problem. What is going on with this article?

strptime使用時に”TypeError:must be string, not int…"が出た時の対処法

More than 1 year has passed since last update.

背景と問題点

勤怠管理の日付を自動で入れるスクリプトあれば便利だな−と思い、
pythonのdatetimeモジュールのstrptimeを使って下記のように書いていた。

Kinkyu.py
input_date = input('作成する年月度を入力して下さい(例:201608):')

try:
    month_first = datetime.datetime.strptime(input_date, '%Y%m')
except ValueError:
        input('年月を201608のように入力して下さい。')
        sys.exit()

すると、年月度を入力した時に下記エラー発生。

month_first = datetime.datetime.strptime(input_date, '%y%m')
TypeError: must be string, not int

原因

あれ?と思って調べてみたら、
どうやらstrptimeの第1引数は文字列が入るとのこと。
数値じゃだめなのね・・・

対処法

int型がNGならString型に変換してあげればよいのでは?と思い、
下記のようにに変更してみた。

Kinkyu.py
input_date = input('作成する年月度を入力して下さい(例:201608):')
input_date = str(input_date) #変更点:数値を文字列に変換

try:
    month_first = datetime.datetime.strptime(input_date, '%Y%m')
except ValueError:
        input('年月を201608のように入力して下さい。')
        sys.exit()

これで解決。pythonだと型変換も楽で良い。

参考リンク

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away