LoginSignup
1
3

More than 5 years have passed since last update.

unixtime←→datetime変換を簡単に行うクラスを作ってみた

Last updated at Posted at 2015-09-24

unixtimeとdatetime(string型)の変換を行うclassを作ってみた

unixtime←→datetimeの変換は結構手間なので簡単に変換できるクラスを作った。

unixtimeは1970年1月1日午前0時を0秒とし、そこから何秒経過したかを示すのに対しdatetimeは人間の目で見慣れたUTC(世界標準時)で表記されるものである。
例えば2015年9月24日23:00分はunixtimeで表記すると「1441303200」で、datetimeで「201509242300」である。

unixtimeをdatetime型への変換はdatetimeモジュールを使えばできるが、datetimeをstring型に変換するのは調べても見つからないので書いてみた。
strftimeを使うとできるそうです。ってことでこのクラスの位置づけは変換を便利にしてみることとしました。

convertTime.py

import datetime
import time


class convertTime:

    def __init__(self,time):
        self.time = time

    def dtime(self):
        date_time =  datetime.datetime.fromtimestamp(self.time)
        date_time = date_time.strftime('%Y%m%d%H%M%S')
        return date_time


    def utime(self):
        self.time = str(self.time)
        assert len(self.time) == 14,"Argument must be 14 character"
        date_time = datetime.datetime(int(self.time[0:4]),int(self.time[4:6]),int(self.time[6:8]),int(self.time[8:10]),int(self.time[10:12]),int(self.time[12:14]))
        return int(time.mktime(date_time.timetuple()))


if __name__ == "__main__":


    d = convertTime(time = 1443103200)
    print "-----------datetime(dtime) to unixtime(utime)----------"
    print d.dtime()

    u =  convertTime(time = 20150924230000)
    print "-----------unixtime(utime) to datetime(dtime)----------"
    print u.utime()



実行結果
-----------datetime(dtime) to unixtime(utime)----------
201509242300
-----------unixtime(utime) to datetime(dtime)----------
1443103200

convertTimeクラスに変換したい時間を投げてやり、.utimeメソッドか.dtimeメソッドで変換する。
今後時間があったらdatetimeでの加算減算が簡単にできる機能を追加したいと思う。

※2015.9.25に訂正しました。ご指摘ありがとうございます。

参考
python2.7 datetime

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