Python中处理时间的模块主要为time和datetime模块,字符串类型时间与时间戳之间的转换要通过时间数组为中介相互转换
1.字符串类型时间转换为时间戳
import time
# 字符类型的时间
time_str = '2018-12-3 20:40:00'
# 转为时间数组,分别利用time模块和datetime模块
timeArray = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
datetimeArray=datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
print (timeArray )#time.struct_time(tm_year=2018, tm_mon=12, tm_mday=3, tm_hour=20, tm_min=40, tm_sec=0, tm_wday=0, tm_yday=337, tm_isdst=-1)
print(datetimeArray)#2018-12-03 20:40:00
# timeArray可以调用tm_year等
print (timeArray.tm_year) #2018
print (timeArray.tm_mon) #12
#datetimeArray可以调用year,hour等
print (datetimeArray.year) #2018
print (datetimeArray.hour) #12
# 转为时间戳
timeStamp = int(time.mktime(timeArray))
timeStamp1=time.mktime(datetimeArray.timetuple())
print (timeStamp) # 1543840800
print (timeStamp1) #1543840800.0
2.时间戳转换为指定格式的字符串类型时间
import time
import datetime
# 使用time
timeStamp = 1543840800
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
print (otherStyleTime) # 2018--12--03 20:40:00
# 使用datetime
timeStamp = 1543840800
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y/%m/%d %H:%M:%S")
print (otherStyleTime) # 2018/12/03 12:40:00
3.获取当前时间并转换为指定格式的字符串类型时间
(除了获取当前时间其实跟前面一样,)
import time
import datetime
# time获取当前时间戳
now = int(time.time())
timeArray = time.localtime(now)
print (timeArray)
timeStamp = int(time.mktime(timeArray))
print(timeStamp)
otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
print (otherStyleTime)
# datetime获取当前时间,数组格式
now = datetime.datetime.now()
print (now)
otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
print (otherStyleTime )
总结下来就是:
字符串类型时间首先要通过time模块里的 strptime或者datetime模块里的datetime.datetime.strptime变成时间数组后再进一步变成时间戳,
时间戳需要通过time模块里的time.localtime或者datetime模块里的datetime.datetime.utcfromtimestamp变成时间数组,再变成字符串,这时也可以重新指定字符串类型时间的格式。