Python Time

Posted by Adam on August 24, 2022
### Python 時間轉換 ```py from datetime import datetime iso8601_str = "2023-04-21T10:30:00" # ISO 8601 格式的日期時間字串 # 解析 ISO 8601 字串並轉換為 UNIX 時間戳(秒數) print(datetime.fromisoformat(iso8601_str).timestamp()) # 輸出:1682073000.0 # 將 UNIX 時間戳轉換為 ISO 8601 格式的字串 print(datetime.fromtimestamp(1682073000).isoformat()) # 輸出:'2023-04-21T10:30:00' # 將 UNIX 時間戳轉換為 datetime 物件 print(datetime.strptime("20211231235959", "%Y%m%d%H%M%S")) # 輸出: 2021-12-31 23:59:59 # 將 UNIX 時間戳轉換為指定字串格式 print(datetime.fromtimestamp(1682073000).strftime("%Y%m%d%H%M%S")) # 輸出:'20230421103000' ``` ### 調整日期 ```py from datetime import datetime, timedelta # 原始日期 original_date = datetime(2023, 4, 21) print(original_date + timedelta(days=1)) # 加一天,輸出: 2023-04-22 00:00:00 print(original_date + timedelta(days=-1)) # 減一天,輸出: 2023-04-20 00:00:00 ``` ### 調整年月 ```py from datetime import datetime from dateutil.relativedelta import relativedelta # 原始日期 original_date = datetime(2023, 4, 21) # 加一個月 next_month = original_date + relativedelta(months=1) # 加一年 next_year = original_date + relativedelta(years=1) print("Next Month:", next_month) # 輸出: Next Month: 2023-05-21 00:00:00 print("Next Year:", next_year) # 輸出: Next Year: 2024-04-21 00:00:00 ``` ### 範圍內隨機一天 ```py import random from datetime import datetime, timedelta # 起始日期和結束日期 start_date = datetime(2023, 1, 1) end_date = datetime(2023, 12, 31) # 計算日期範圍的天數 days_range = (end_date - start_date).days # 隨機生成一個範圍內的天數偏移量 random_days_offset = random.randint(0, days_range) # 根據偏移量計算隨機日期 random_date = start_date + timedelta(days=random_days_offset) print("Random Date:", random_date) ```