1. 程式人生 > 其它 >python常用工具類總結之——獲取時間timeTool

python常用工具類總結之——獲取時間timeTool

托爾斯泰

------------恢復內容開始------------

------------恢復內容開始------------

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '操作時間的工具類'

"""
import datetime
import time


# ==========================
# ========== time ==========
# ==========================


def getCurrentMilliSecondTime():
"""
description: 獲取當前時間-毫秒級
return: 1557730376981 -> str
"""
timestamps = str(round(time.time() * 1000))
return timestamps


def getCurrentSecondTime():
"""
description: 獲取當前時間-秒級
return: 1557730377 -> str
"""
timestamps = str(round(time.time()))
return timestamps


def getCurrentTimeTuple(times=time.time()):
"""
description: 接受秒級時間戳並返回時間元組(與mktime(tuple)相反)
times: 預設當前時間 可傳second
return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
tips: time.localtime() 不傳參則取當前時間
"""
timestamps = time.localtime(times)
return timestamps


def getTimeByTuple(tupleTime=time.localtime()):
"""
description: 接受時間元組並返回秒級時間戳(與localtime(sec)相反)
tupleTime: 預設當前時間的元組 可通過time.localtime() or datetime.datetime.now().timetuple()獲取
return: 1557733061 -> str
"""
timestamps = str(round(time.mktime(tupleTime)))
return timestamps


def getCurrentFormatTimeStr(times=time.time()):
"""
description: 將指定時間元組格式化為字串
times: 預設當前時間 可傳second
return: 2019-05-13 15:00:47 -> str
tips: %y 兩位數的年份表示(00-99) %Y 四位數的年份表示(000-9999) %m 月份(01-12) %d 月內中的一天(0-31)
%H 24小時制小時數(0-23) %I 12小時制小時數(01-12) %M 分鐘數(00=59) %S 秒(00-59) %w 星期(0-6)
"""
timestamps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
return timestamps


def getCurrentTimeTupleByFormatStr(time_str=str(datetime.datetime.now()).split(".")[0],
format_type="%Y-%m-%d %H:%M:%S"):
"""
description: 接受格式化字串返回時間元組
time_str: 格式化字串 如:2019-05-13 15:00:47 預設當前時間
format_type: 格式化規則 如:%Y-%m-%d %H:%M:%S 預設%Y-%m-%d %H:%M:%S
return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
"""
return time.strptime(time_str, format_type)


def getCurrentTimeStr():
"""
description: 獲取當前時間的可讀形式字串
return: Mon May 13 11:27:42 2019 -> str
"""
return time.ctime()


def getCurrentTimeStrByTuple(tupleTime=time.localtime()):
"""
description: 獲取指定時間的可讀形式字串
tupleTime: 時間元組 可通過time.localtime() or datetime.datetime.now().timetuple()獲取 預設當前時間的元組
return: Mon May 13 11:27:42 2019 -> str
"""
return time.asctime(tupleTime)


def sleepTime():
"""
description: 推遲呼叫執行緒的執行
"""
for i in range(4):
print(i)
time.sleep(3)

# ======================


# ====== datetime ======
# ======================


def getNowDateTime():
"""
description: 獲取當前日期&時間
return: 2019-05-13 14:41:15 -> str
"""
timestamps = str(datetime.datetime.now()).split(".")[0]
return timestamps


def getNowTime():
"""
description: 獲取當前時間
return: 14:41:15 -> str
"""
timestamps = str(datetime.datetime.now().time()).split(".")[0]
return timestamps


def getTodayDate():
"""
description: 獲取當前日期
return: 2019-05-13 -> str
tipe: datetime.datetime.now().date()有相同效果
"""
timestamps = str(datetime.date.today())
return timestamps


def getTimeDate(times=time.time()):
"""
description: 獲取指定時間戳的日期
time: 秒 預設當前時間
return: 2019-05-13 -> str
tips: 一天86400秒
"""
timestamps = str(datetime.date.fromtimestamp(round(times)))
return timestamps

# 獲取距離現在時間的任意時間的日期 正數 加,負數 減 return:2019-05-12


def getAnyDateTime(day, hour=0, min=0, sec=0):
"""
description: 獲取距離現在時間的任意時間的日期&時間
day: 天數 1代表當前時間+1天 -1代表當前時間-1天
hour: 小時 2代表當前時間+2h -2代表當前時間-2h 預設=0
min: 分鐘 30代表當前時間+30min -30代表當前時間-30m 預設=0
sec: 秒 120代表當前時間+120s -120代表當前時間-120s 預設=0
return: 2019-05-15 15:37:41 -> str
"""
return str(datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)).split(".")[
0]


def getAnyDateSecondTime(day, hour=0, min=0, sec=0):
"""
description: 獲取距離現在時間的任意時間的秒數
day: 天數 1代表當前時間+1天 -1代表當前時間-1天
hour: 小時 2代表當前時間+2h -2代表當前時間-2h 預設=0
min: 分鐘 30代表當前時間+30min -30代表當前時間-30m 預設=0
sec: 秒 120代表當前時間+120s -120代表當前時間-120s 預設=0
return: 1557902182 -> str
"""
anyDay = datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)
return str(round(time.mktime(anyDay.timetuple())))


def getTodayTime():
"""
description: 獲取當天0點的時間戳
return: 1557676800 -> str
"""
return str(round(time.mktime(datetime.date.today().timetuple())))


def getCurrentWeekTime():
"""
description: 獲取本週週一0點
return: 1557676800 -> str
tips: 可替換成: timestamps = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(times)), "%Y-%m-%d"))
"""
week = int(time.strftime("%w", time.localtime()))
times = round(time.time()) - (week - 1) * 86400
timestamps = time.mktime(datetime.date.fromtimestamp(times).timetuple())
return str(round(timestamps))


def test():
print(getCurrentMilliSecondTime())
print(getCurrentSecondTime())
print(getCurrentFormatTimeStr())
print(getCurrentTimeTupleByFormatStr())
print("=======")
print(getCurrentTimeStr())
print(getCurrentTimeStrByTuple(time.localtime()))
print(getTimeByTuple(time.localtime()))
print("=======")
print(getNowDateTime())
print(getNowTime())
print(getNowDateTime())
print(getTodayDate())
print(getTimeDate(time.time() - 86400))
print("=======")
print(getAnyDateTime(2))
print(getAnyDateSecondTime(2))
print("=======")
print(getTodayTime())
print(getCurrentWeekTime())

if __name__ == '__main__':
print(test())

------------恢復內容結束------------

------------恢復內容結束------------