python

python打印时间的方法有哪些

小亿
260
2024-01-27 14:21:17
栏目: 编程语言

Python打印时间的方法有以下几种:

  1. 使用time模块:通过time模块的time()函数获取当前时间戳,然后使用asctime()函数将时间戳转换为可读性更好的格式。
import time
print(time.asctime(time.localtime(time.time())))
  1. 使用datetime模块:通过datetime模块的datetime类创建一个datetime对象,然后使用strftime()方法将其格式化为指定的字符串。
import datetime
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1. 使用calendar模块:通过calendar模块的Calendar类创建一个calendar对象,然后使用formatyear()方法将其格式化为指定的字符串。
import calendar
print(calendar.calendar(2021))
  1. 使用strftime()函数:通过strftime()函数将时间格式化为指定的字符串。
import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

注意:以上方法都只是打印当前时间,如果需要打印指定时间可以使用相关的参数进行设置。

1
看了该问题的人还看了