python 中 日期,時間戳的轉換
阿新 • • 發佈:2019-01-22
一,日期轉換成為時間戳
1,首先需要引入模組,time ,datetime
import time ,datetime
2,把輸入的字元轉換成為陣列
# Python time strptime() 函式根據指定的格式把一個時間字串解析為時間元組。 # time.strptime(string[, format]) tsl = "2016-10-10" # 轉為時間陣列 timeArray = time.strptime(tsl, "%Y-%m-%d") #如果有精確時間,如"2016-10-10 10:10:40" timeArray = time.strptime(ts1, "%Y-%m-%d %H:%M:%S")
其中print(timeArray)的執行結果是:
time.struct_time(tm_year=2016, tm_mon=10, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=284, tm_isdst=-1)
print(timeArray.tm_year) 的執行結果是 2016
3,把時間轉換為時間戳
# 轉為時間戳 //mktime()用來將引數timeptr所指的tm結構資料轉換成從公元1970年1月1日0時0分0 秒算起至今的時間所經過的秒數。 timeStamp = int(time.mktime(timeArray))
print(timeStamp)的執行結果為 1476028800
二,時間戳轉換成為日期
1,同樣使用模組 time ,datetime
使用time
timeStamp = 1381419600 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) print otherStyleTime # 2013--10--10 23:40:00 #localtime() 函式返回本地時間(一個數組)。 #localtime() 的第一個引數是時間戳,如果沒有給出則使用從 time() 返回的當前時間。
使用datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
print otherStyleTime # 2013--10--10 15:40:00
三,更改時間顯示的格式
tss2 = "2013-10-10 23:40:00"
# 轉為陣列
timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")
# 轉為其它顯示格式
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print otherStyleTime # 2013/10/10 23:40:00
tss3 = "2013/10/10 23:40:00"
timeArray = time.strptime(tss3, "%Y/%m/%d %H:%M:%S")
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print otherStyleTime # 2013-10-10 23:40:00
四,獲取當前時間並用指定格式顯示
# time獲取當前時間戳
import time
now = int(time.time()) # 1533952277 返回當前時間的時間戳
print(now)
timeArray = time.localtime(now) # 根據時間戳返回當前資料
print(timeArray)
otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) # 按照指定格式顯示
print(otherStyleTime)
# datetime獲取當前時間,陣列格式
import datetime
now = datetime.datetime.now() # 返回當前時間,以“%Y-%m-%d %H:%M:%S”格式
print (now)
otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S") # 按照指定格式顯示
print (otherStyleTime)