import math import time from datetime import datetime # 轉換時間格式到字串(天) def human_date(date=None): if date: assert isinstance(date, datetime) else: date = datetime.now() return date.strftime("%Y-%m-%d") # 轉換時間格式到字串 def human_datetime(date=None): if date: assert isinstance(date, datetime) else: date = datetime.now() return date.strftime("%Y-%m-%d %H:%M:%S") def human_time(date=None): if date: assert isinstance(date, datetime) else: date = datetime.now() return date.strftime("%H:%M:%S") # 解析時間類型的資料 def parse_time(value): if isinstance(value, datetime): return value if isinstance(value, str): if len(value) == 10: return datetime.strptime(value, "%Y-%m-%d") elif len(value) == 19: return datetime.strptime(value, "%Y-%m-%d %H:%M:%S") raise TypeError("Expect a datetime.datetime value") # 傳兩個時間得到一個時間差 def human_seconds_time(seconds): text = "" if seconds >= 3600: text += "%d小時" % (seconds / 3600) seconds = seconds % 3600 if seconds >= 60: text += "%d分" % (seconds / 60) seconds = seconds % 60 if seconds > 0: if text or isinstance(seconds, int): text += "%.d秒" % seconds else: text += "%.1f秒" % seconds return text def seconds_for_human(seconds): second = 1 minute = second * 60 hour = minute * 60 day = hour * 24 lst = [] if seconds >= day: days, seconds = divmod(seconds, day) lst.append(str(days) + "d") if seconds >= hour: hours, seconds = divmod(seconds, hour) lst.append(str(hours) + "h") if seconds >= minute: minutes, seconds = divmod(seconds, minute) lst.append(str(minutes) + "m") if seconds > 0: lst.append(str(seconds) + "s") return " ".join(lst) def time_for_human(time_val): second = 1 minute = second * 60 hour = minute * 60 day = hour * 24 days_8 = day * 8 if isinstance(time_val, datetime): time_val = time_val.timestamp() if isinstance(time_val, str): time_val = time.mktime(time.strptime(time_val, "%Y-%m-%d %H:%M:%S")) now = time.time() duration = now - time_val if duration < minute: return "剛剛" elif duration < hour: return str(math.floor(duration / minute)) + "分鐘前" elif duration < day: return str(math.floor(duration / hour)) + "小時前" elif duration < days_8: return str(math.floor(duration / day)) + "天前" else: return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_val)) if __name__ == "__main__": print(human_datetime()) print(human_date()) print(human_time()) print(human_seconds_time(10)) print(seconds_for_human(86400 + 3600)) print(parse_time("2022-10-17 13:33:11")) print(time_for_human(1665381270)) print(time_for_human(time.time() - 100)) print(time_for_human("2022-10-17 13:33:11"))