LoginSignup
0
6

More than 3 years have passed since last update.

Pythonで日付のタイムゾーン(時差)を変換(文字列から)

Posted at

思いがけずどツボにハマったので忘備録です。もっと楽なのありそうですがいったんこれで。

やりたいこと→文字列の日付(標準時間)を日本時間に直したい

#importするのはこれだけでOK
import datetime

#元の日付(標準時間)
hiduke = '25/Aug/2020 11:01:52'

#1. 日付型に変換
hiduke = datetime.datetime.strptime(hiduke, '%d/%b/%Y %H:%M:%S')

#2. タイムゾーンの情報を付与(ここではUTC)
hiduke = hiduke.replace(tzinfo=datetime.timezone.utc)

#3. タイムゾーンを日本時間に変換
+9時間
hiduke = hiduke.astimezone(datetime.timezone(datetime.timedelta(hours=+9)))

#4. タイムゾーン表記を消去
hiduke = hiduke.replace(tzinfo=None)

1.日付型に変換

  • strrptime = String (to be) Replace(ed by) Time をつなげたものかと思われます。
  • 引数には、変換したい日付(文字列)、およびその日付がどんな表記で書かれているのかを明記します。
  • %d = 日
  • %b = 月(Aug)。月の名前の省略形。なお、数字の月の場合は %m, Augustの場合は %B
  • %Y = 年
  • 2020-08-26 であれば、 %Y-%m-%dと表記。
  • 表記一覧はこちらに載っています。 Pythonのdatetimeで日付や時間と文字列を変換(strftime, strptime)

2. タイムゾーンの情報を付与(ここではUTC)

tzinfo = timezone info.

3. タイムゾーンを日本時間に

日本時間は標準時間+9時間のため。 hours=+9 となります。実際の表記は datetime.timedelta(hours=+9)

4. タイムゾーン表記を消去

③のままだと日付の後ろに +09:00 (タイムゾーン表記)がくっついてしまうので、tzinfo=Noneにすることで消すことができます。
これで、 25/Aug/2020 11:01:52 が 2020-08-25 20:01:52 となります。

参考

Python, datetime, pytzでタイムゾーンを設定・取得・変換・削除

Pythonで文字列 <-> 日付(date, datetime) の変換

0
6
0

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
0
6