# -*- coding: utf-8 -*- import time def timestamp_datetime(value): format = '%Y-%m-%d %H:%M:%S' # value爲傳入的值爲時間戳(整形),如:1332888820 value = time.localtime(value) ## 通過localtime轉換後變成 ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0) # 最後再通過strftime函數轉換爲正常日期格式。 dt = time.strftime(format, value) return dt def datetime_timestamp(dt): #dt爲字符串 #中間過程,通常都須要將字符串轉化爲時間數組 time.strptime(dt, '%Y-%m-%d %H:%M:%S') ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1) #將"2012-03-28 06:53:40"轉化爲時間戳 s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S')) return int(s) if __name__ == '__main__': d = datetime_timestamp('2012-03-28 06:53:40') print d s = timestamp_datetime(1332888820) print s