問題の起きたコード
Twitter API でツイートの投稿時間(created_at)を日本時間(△年〇月×日)に変換しようとした時のコードです。
import time, locale, calendar def getTimeFormat(twitterTime, format): formatTime = "" try: time_utc = time.strptime(twitterTime, '%a %b %d %H:%M:%S +0000 %Y') unix_time = calendar.timegm(time_utc) time_local = time.localtime(unix_time) locale.setlocale(locale.LC_ALL, 'ja_JP.UTF-8') print(locale.getlocale(locale.LC_ALL)) formatTime= time.strftime(format, time_local) except: print("エラー:" + twitterTime) return formatTime tweets = (ツイート一覧を取得するコード) for tweet in tweets: created_at = tweet['created_at'] japanDate = getTimeFormat(created_at, '%Y年%m月%d日') print(japanDate)
みたいなコードを書いたら、1ループ目は問題なかったですが、2ループ目から、以下のようなエラーになりました。
ValueError: time data 'Tue May 05 07:37:08 +0000 2015' does not match format '%a %b %d %H:%M:%S +0000 %Y'
原因
原因はこれですね。
locale.setlocale(locale.LC_ALL, 'ja_JP.UTF-8')
これによって日本語に対応するのが可能になりましたが、その代わりに別の何かが識別できなくなったようです。
おそらくは月とか曜日のところですね。英語の部分はja_JPじゃダメなのかも。
解決策
UTCの時間を読み込むときは、ロケールをデフォルトに戻せば良いかと思います。
デフォルトのロケールを確認してみましょう。
print(locale.getlocale(locale.LC_ALL))
結果
(None, None)
よって、('ja_JP', 'UTF-8')を(None, None)に戻してあげれば良いです。
import time, locale, calendar def getTimeFormat(self, twitterTime, format): formatTime= "" try: locale.setlocale(locale.LC_ALL, (None,None)) time_utc = time.strptime(twitterTime, '%a %b %d %H:%M:%S +0000 %Y') unix_time = calendar.timegm(time_utc) time_local = time.localtime(unix_time) locale.setlocale(locale.LC_ALL, 'ja_JP.UTF-8') print(locale.getlocale(locale.LC_ALL)) formatTime= time.strftime(format, time_local) except: print("エラー:" + twitterTime) return formatTime tweets = (ツイート一覧を取得するコード) for tweet in tweets: created_at = tweet['created_at'] japanDate = getTimeFormat(created_at, '%Y年%m月%d日') print(japanDate)
追加したのは下記です。
locale.setlocale(locale.LC_ALL, (None,None))