獲取當前時間:
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(localtime) #打印: 2022-01-04 19:44:47 進程已結束,退出代碼為 0
獲取當前時間戳:如果想讓小數點后移,則*10即可
import time
localtime = time.time() print(localtime)
# 打印
1641297004.802891
# 想去掉小數點加int
時間與時間戳之間的轉換:
import time # 時間轉換成時間戳 tss1 = '2022-03-29 00:00:00' timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) print(timeStamp) # 10位時間戳轉換成時間 timeStamp = 1648483200 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)
# 13位時間戳轉成時間 tre_timeArray = time.localtime(1646012206685/1000) tre_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", tre_timeArray) print('tre_otherStyleTime',tre_otherStyleTime)
>>>1648483200 >>>2022-03-29 00:00:00
時間和日期的加減:
from datetime import datetime from dateutil.relativedelta import relativedelta # 加1年 print((datetime.now() + relativedelta(years=1)).strftime("%Y-%m-%d")) # 加1個月 print((datetime.now() + relativedelta(months=1)).strftime("%Y-%m-%d")) # 加1天 print((datetime.now() + relativedelta(days=1)).strftime("%Y-%m-%d")) # 加1小時 print((datetime.now() + relativedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")) # 加1分鍾 print((datetime.now() + relativedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")) 打印結果 2023-06-29 2022-07-29 2022-06-30 2022-06-29 17:07:58 2022-06-29 16:08:58
日期的隔差:
import datetime from dateutil import rrule d1 = datetime.date(2021, 9, 26) d2 = datetime.date(2022, 2, 11) months = rrule.rrule(rrule.MONTHLY, dtstart=d1, until=d2).count() print("兩者日期隔差為:", f"months={months}") 打印結果 兩者日期隔差為: months=5
打印各種格式日期:
import time # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 將格式字符串轉換為時間戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))) 打印結果 2022-06-29 16:18:10 Wed Jun 29 16:18:10 2022 1459175064.0
