LoginSignup
3
3

More than 5 years have passed since last update.

Python2.7 で タイムゾーン付き日時を Unixtime に変換する

Last updated at Posted at 2016-04-16

やりたかっこと

ISO 8601 YYYYMMDDThhmmss.SSS+900 を Unixtime に変換しようとしていた。
python2.7 で strptime では %z がサポートされていないので、タイムゾーンを使った日付変換が面倒くさい。%z を使うと下記のように怒られる。
ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'

strftime() と strptime() を使ってtzinfo付きdatetime <-> stringの変換をやってみた を参考に途中までやっていたのだが、 JST から JST の変換はゾーン指定子を気にする必要がなかったことに気づいた。
※UTCからJSTへの変換などは上記の記事のようなことが必要だろう。

タイムゾーン指定子を削除してしまえばいい

タイムゾーン
使えないなら
消してしまえ

>>> from datetime import datetime
>>> import time
>>> int(time.mktime(datetime.strptime('20160323T204100.001+0900'.replace('+0900', ''), '%Y%m%dT%H%M%S.%f').timetuple()))                                       
1458733260

ちょっと強引だけどシンプルになった。

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