You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.05 08:22:01