你首先要做的是像这样导入 datetime
模块
from datetime import datetime
接下来你可以做的是使用 datetime
模块中的 datetime.now()
函数来快速获得当前日期和时间。
from datetime import datetime
currentDateAndTime = datetime.now()
print("The current date and time is", currentDateAndTime)
要获得当前时间,你可以使用 strftime()
方法,并向其传递代表小时、分钟和秒的字符串 ”%H:%M:%S”
。
这将给你提供 24 小时格式的当前时间。
from datetime import datetime
currentDateAndTime = datetime.now()
print("The current date and time is", currentDateAndTime)
# Output: The current date and time is 2022-12-26 10:07:50.369647
currentTime = currentDateAndTime.strftime("%H:%M:%S")
print("The current time is", currentTime)
# The current time is 10:07:50