Python 极简时间转换

import datetime
import time

now = datetime.datetime.now()

timestamp = time.mktime(now.timetuple())
print "datetime -> timestamp :", now, " -> ", timestamp
now = datetime.datetime.fromtimestamp(timestamp)
print "timestamp -> datetime :", timestamp, " -> ", now

now_string = now.strftime("%Y-%m-%d %H:%M:%S")
print "datetime -> string :", now, " -> ", now_string
now = datetime.datetime.strptime(now_string, "%Y-%m-%d %H:%M:%S")
print "string -> datetime :", now_string, " -> ", now

输出:

datetime -> timestamp : 2017-01-17 21:29:03.221580  ->  1484659743.0
timestamp -> datetime : 1484659743.0  ->  2017-01-17 21:29:03
datetime -> string : 2017-01-17 21:29:03  ->  2017-01-17 21:29:03
string -> datetime : 2017-01-17 21:29:03  ->  2017-01-17 21:29:03

timestamp -> datetime -> string 以 datetime 为中间变量

你可能感兴趣的:(Python 极简时间转换)