如何用Python创建Clock类并实现current_time方法获取当前时间?
Python实现Clock类打印当前时间
你可以借助Python内置的datetime模块来实现这个需求,以下是完整的代码示例:
import datetime class Clock: def current_time(self): # 获取当前本地时间并格式化输出 now = datetime.datetime.now() formatted_time = now.strftime("%Y-%m-%d %H:%M:%S") print(formatted_time) # 测试功能 if __name__ == "__main__": clock = Clock() clock.current_time()
代码说明:
import datetime:导入Python自带的日期时间模块,用于获取系统当前时间class Clock::定义名为Clock的类def current_time(self)::在类中定义current_time方法,self是类方法的必填参数,用来指代类的实例对象datetime.datetime.now():获取当前的本地日期和时间strftime("%Y-%m-%d %H:%M:%S"):将时间对象格式化为易读的字符串格式,你可以按需调整格式,比如只显示时分秒可改为"%H:%M:%S"
如果不需要格式化,直接打印原始时间对象也可以,修改方法如下:
def current_time(self): print(datetime.datetime.now())
内容的提问来源于stack exchange,提问作者David Ifeoluwa Praise Ebi-Fred
相关产品推荐
相关产品推荐

