python - 生成時間範圍

wstong發表於2024-11-13

例如生成07:45-08:30範圍的時間

import datetime, random
date1 = datetime.datetime(2022, 1, 1, 7, 45, 0)
date2 = datetime.datetime(2022, 1, 1, 8, 30, 0)
timestamp1 = date1.timestamp()
timestamp2 = date2.timestamp()
datetime.datetime.fromtimestamp(timestamp1 + random.randint(0, timestamp2-timestamp1)).strftime("%H:%M")

相關文章