python共通日付時間関数

2298 ワード

import datetime
import time

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
print('   :%s' % yesterday)     #    :2018-12-04
print('   :%s' % today)         #    :2018-12-05
print('   :%s' % tomorrow)      #    :2018-12-06
today_str = str(today)
print(type(today))  # 
print(today)  # 2018-12-05

print(type(today_str))  # 
print(today_str)  # 2018-12-05


print(datetime.time())  # 00:00:00
print(datetime.datetime.now())  # 2018-12-05 11:04:25.231688

time_stmp = time.time()
print(time_stmp)  # 1543979065.2316968
print(type(time_stmp))  # 

local_time = time.localtime()
print(local_time)  # time.struct_time(tm_year=2018, tm_mon=12, tm_mday=5, tm_hour=11, tm_min=4, tm_sec=25, tm_wday=2, tm_yday=339, tm_isdst=0)
print(type(local_time))  # 
strftime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(strftime)  # 2018-12-05 11:04:25
print(type(strftime))  # 

now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  #     
print(now_time)  # 2018-12-05 11:04:25
print(type(now_time))  # 

now_data_str = datetime.datetime.now().strftime("%Y-%m-%d")
now_time_str = datetime.datetime.now().strftime("%H:%M:%S")
print(now_data_str,type(now_data_str))  # 2018-12-05 
print(now_time_str,type(now_time_str))  # 11:04:25   

import time


class Tool():
    #       
    def timestamp2datetime(self,timestamp):
        time_local = time.localtime(timestamp)
        datetime = time.strftime("%Y-%m-%d %H:%M:%S",time_local)
        return datetime

    #       
    def datetime_str2timestamp(self, datestr):
        """
        datestring translate to timestamp
        :param datestr:
        :return:
        """
        timeArray = time.strptime(datestr, "%Y-%m-%d %H:%M:%S")
        timeStamp = int(time.mktime(timeArray))
        return timeStamp


if __name__ == "__main__":
    t = Tool()
    timestamp = 1548376037
    dt = t.timestamp2datetime(timestamp)
    print(dt)
    ts = t.datetime_str2timestamp(dt)
    print(ts)