一、字符串與為時間字符串之間的互相轉換
方法:time模塊下的strptime方法
a = "2012-11-11 23:40:00" # 字符串轉換為時間字符串 import time timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") # 時間字符串轉換為字符串 b = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) print(type(b))# <class 'str'>
二、將字符串的時間轉換為時間戳
方法:字符串 --> 時間字符串 --> 時間戳
a = "2013-10-10 23:40:00" # 將其轉換為時間數組 import time timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") # 轉換為時間戳: timeStamp = int(time.mktime(timeArray)) print(timeStamp)#1381419600
三、得到時間戳(10位和13位)
import time t = time.time() print(t) # 1436428326.207596 t_10 = int(t)# 10位時間戳 t_13 = int(round(time.time() * 1000))# 13位時間戳 print(t_10)# 1436428326 print(t_13)# 1436428326207
四、將時間戳轉換為時間格式的字符串
方法一:利用localtime()轉換為時間數組,然后格式化為需要的格式
timeStamp = 1381419600# 10位時間戳 # timeStamp_13 = 1381419600234# 13位時間戳 timeArray = time.localtime(timeStamp)# timeStamp_13 / 1000 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyletime)# "2013-10-10 23:40:00"(str)
方法二、利用datetime模塊下的utcfromtimestamp方法
import datetime timeStamp = 1381419600 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S") print(otherStyletime) # "2013-10-10 23:40:00"
五、時間字符串轉換為時間戳
方法:利用time模塊的mktime方法
import time import datetime # 先獲得時間數組格式的日期 test_date = datetime.datetime.now() # 轉換為時間戳: timeStamp = int(time.mktime(test_date.timetuple()))
六、時間字符串加減日期
方法:利用datetime模塊下的timedelta方法
import time import datetime # 先獲得時間數組格式的日期 test_datetime = datetime.datetime.now() threeDayAgo = (test_datetime - datetime.timedelta(days = 3))# 3天前 # 注:timedelta()的參數有:days,hours,seconds,microseconds
七、獲取 UTC 時間戳
import calendar calendar.timegm(datetime.datetime.utcnow().timetuple())
八、python 格式化時間含中文報錯 UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence'
import time print(time.strftime(u'%Y年%m月%d日',time.localtime(time.time()))) # 執行上面代碼會報錯 UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence # 解決方式: time.strftime('%Y{y}%m{m}%d{d}').format(y='年',m='月',d='日')