1. 程式人生 > >python3(十位時間戳)時間戳獲取昨天,前天等

python3(十位時間戳)時間戳獲取昨天,前天等

import time
import datetime
# 今天日期
today = datetime.date.today()
print(today)
# 昨天時間
yesterday = today - datetime.timedelta(days=1)
print(yesterday)
# 明天時間
tomorrow = today + datetime.timedelta(days=1)
acquire = today + datetime.timedelta(days=2)
# 昨天開始時間戳
yesterday_start_time = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))
print(yesterday_start_time)
# 昨天結束時間戳
yesterday_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) - 1
print(yesterday_end_time)
# 今天開始時間戳
today_start_time = yesterday_end_time + 1
# 今天結束時間戳
today_end_time = int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d'))) - 1
# 明天開始時間戳
tomorrow_start_time = int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d')))
# 明天結束時間戳
tomorrow_end_time = int(time.mktime(time.strptime(str(acquire), '%Y-%m-%d'))) - 1

參考文章https://www.cnblogs.com/jason-lv/p/8260539.html(這裡面結構化時間、字串時間、時間戳關係比較重要)

在這裡插入圖片描述

(1)時間戳 -> 結構化時間
複製程式碼
#(1)時間戳 -> 結構化時間
#time.gmtime() #UTC時間,與英國倫敦當地時間一致
#time.localtime() #當地時間
print(time.gmtime(1500000000))
‘’‘結果:
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
‘’’
print(time.localtime(1500000000))
‘’’
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
‘’’

#兩個時間比較發現本地時間比UTC時間快8個小時
複製程式碼
(2)結構化時間 -> 時間戳
#(2)結構化時間 -> 時間戳
time_tuple = time.localtime(1500000000)
print(time.mktime(time_tuple)) #mktime函式接收struct_time物件作為引數,返回用秒數來表示時間的浮點數。
‘’‘結果:
1500000000.0
‘’’
(3)結構化時間 -> 字串時間
#(3)結構化時間 -> 字串時間
print(time.strftime(’%Y-%m-%d’,time.localtime(time.time())))
‘’‘結果:
2018-01-10
‘’’
(4)字串時間 -> 結構化時間
複製程式碼
#(4)字串時間 -> 結構化時間
#time.strptime(時間字串,字串對應格式)
print(time.strptime(“2017-03-16”,"%Y-%m-%d"))
‘’‘結果:
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1)
‘’’
複製程式碼