LoginSignup
4
3

More than 5 years have passed since last update.

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

Posted at

背景と問題点

勤怠管理の日付を自動で入れるスクリプトあれば便利だな−と思い、
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だと型変換も楽で良い。

参考リンク

4
3
2

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
4
3