
python 怎么获取当前时间
用户关注问题
如何在Python中获取系统的当前日期和时间?
我想在Python程序中获取当前的日期和时间,有什么简单的方法可以实现吗?
使用datetime模块获取当前日期和时间
可以使用Python内置的datetime模块来获取当前日期和时间。通过导入datetime模块,然后调用datetime.datetime.now()函数即可获得当前的本地日期和时间。例如:
import datetime
current_time = datetime.datetime.now()
print(current_time)
怎样以指定格式显示Python中的当前时间?
得到当前时间后,如何把它格式化成比如“年-月-日 时:分:秒”的形式?
使用strftime方法格式化时间显示
datetime对象支持strftime方法,可以自定义时间的输出格式。例如,要将当前时间格式化成“2024-06-01 14:30:00”这样的字符串,可以这样写:
import datetime
current_time = datetime.datetime.now()
formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_time)
Python中获取当前时间还有哪些其他模块或方法?
除了datetime模块之外,有没有其他模块或者函数也能用来获取当前时间?
使用time模块获取当前时间
除了datetime模块,Python的time模块也可以用来获取当前时间。例如,使用time.localtime()可以获取时间元组,然后通过time.strftime()对其格式化:
import time
current_time = time.localtime()
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', current_time)
print(formatted_time)