strftime函數是Python中用于格式化日期和時間的函數,可以將日期和時間對象轉換為特定格式的字符串。以下是一些strftime函數在時間處理中的技巧:
import datetime
now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
輸出結果類似于:2021-10-26 14:30:00
weekday = now.strftime("%A")
print(weekday)
輸出結果為星期幾的全稱,比如:Tuesday
custom_format = now.strftime("Today is %A, %B %d, %Y. The time is %I:%M %p.")
print(custom_format)
輸出結果為類似于:Today is Tuesday, October 26, 2021. The time is 02:30 PM.
timestamp = 1635225000
date_time = datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
print(date_time)
輸出結果類似于:2021-10-26 14:30:00