天天看點

python 下日期和時間戳互相轉換方法

時間戳轉成日期

import time,datetime

####################################################
# 時間戳轉成日期
#####################################################
# 獲得目前時間時間戳
now = int(time.time())
#轉換為其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

# 獲得目前時間
now = datetime.datetime.now()
# 轉換為指定的格式
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

# 指定時間戳
timeStamp = 1589857200
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

# 指定時間戳( 使用datetime,指定utc時間,相差8小時)
timeStamp=1589857200
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

           

日期轉成時間戳

import time,datetime
####################################################
# 日期轉成時間戳
#####################################################
print('日期轉成時間戳')
# 字元類型的時間
tss1 = '2020-05-19 11:00:00'
# 轉為時間數組
timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
print(timeArray)
# timeArray可以調用tm_year等
print(timeArray.tm_year)

# 轉為時間戳
timeStamp = int(time.mktime(timeArray))
print(timeStamp)


# # 結果如下
# time.struct_time(tm_year=2013, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=283, tm_isdst=-1)
# 2013
# 1381419600