LoginSignup
1
4

More than 5 years have passed since last update.

python2.7で日付型のオブジェクトをunixtimeに変換する

Last updated at Posted at 2018-10-07

python2.7の日付型のオブジェクトをunixtimeに変換してあげる必要があったんですが、関数一発で変換できない悲しみ。
備忘録も兼ねて記事に。

動作確認ッ!

Qiitaにもpaiza.ioみたいな感じでwebから動作確認できる、お砂場が欲しい……:yum:

コード内容ッ!

unixtime.py
import time
from datetime import datetime, date

def convert_unix_time(datetime_obj):
    return int(time.mktime(datetime_obj.timetuple()))

print convert_unix_time(datetime.now())

# 1538919464

と、こんな感じです。
timetupleで変換したものを、mktimeに渡して、そしてそれをInt型に落としています……!

しかし、値を取りたかっただけなのに、こんなめんどくさいことに。
他に上手い実装方法はないのだろうか:thinking:

追記

python3ならtimestamp関数があるので、こんな不便なことには……:sob:

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