Converting unixtime ← → datetime is quite troublesome, so I made a class that can be easily converted.
The unix time is set to 0 seconds on January 1, 1970 at midnight, and indicates how many seconds have passed since then, while the date time is expressed in UTC (Coordinated Universal Time), which is familiar to the human eye. For example, 23:00 on September 24, 2015 is "1441303200" in unix time and "201509242300" in date time.
You can convert ~~ unixtime to datetime type by using the datetime module, but I can't find how to convert datetime to string type, so I wrote it. ~~ It seems that you can do it by using strftime. So I decided to position this class to make the conversion convenient.
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()
Execution result
-----------datetime(dtime) to unixtime(utime)----------
201509242300
-----------unixtime(utime) to datetime(dtime)----------
1443103200
Throw the time you want to convert to the convertTime class and convert it with the .utime method or .dtime method. If I have time in the future, I would like to add a function that makes it easy to add and subtract with datetime.
Reference python2.7 datetime
Recommended Posts