Python获取当前时间的几种方法
Python语言获取当前时间的几种方法:
- 使用time模块
- 使用datetime模块
- 使用calendar模块
使用time模块获取当前时间:
import time
# 获取当前时间戳
timestamp = time.time()
# 转换成localtime
local_time = time.localtime(timestamp)
# 转换成新的时间格式(2016-05-09 18:59:20)
dt = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(dt)
使用datetime模块获取当前时间:
from datetime import datetime
# 获取当前时间
now = datetime.now()
# 转换成指定的格式
dt = now.strftime('%Y-%m-%d %H:%M:%S')
print(dt)
使用calendar模块获取当前时间:
import calendar # 获取当前时间 now = datetime.datetime.now() # 获取当前日历 cal = calendar.month(now.year, now.month) print(cal)
以上就是Python获取当前时间的几种方法,他们都有自己的优点和缺点,根据实际情况选择合适的方法使用即可。