欢迎访问宙启技术站
智能推送

Python编码技巧:使用now()函数获取当前时间并在输出中进行格式化处理

发布时间:2024-01-05 23:04:39

在 Python 中,可以使用 datetime 模块的 datetime 类来获取当前日期和时间。为了格式化输出时间,可以使用 strftime 方法。

下面是一个使用 now() 函数获取当前时间并进行格式化处理的例子:

from datetime import datetime

# 使用now()函数获取当前时间
current_time = datetime.now()

# 格式化输出时间
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

# 输出格式化后的时间
print("当前时间:", formatted_time)

上述例子中,now() 函数用于获取当前时间,strftime() 方法用于格式化时间。在 strftime() 方法的参数中,可以使用不同的格式化指令来显示不同的时间格式。

以下是一些常用的格式化指令:

- %Y:四位数的年份(例如:2022)

- %m:两位数的月份(01 至 12)

- %d:两位数的日期(01 至 31)

- %H:小时(00 至 23)

- %M:分钟(00 至 59)

- %S:秒(00 至 59)

此外,还可以使用其他格式化指令来显示更具体的时间格式,例如使用 %A 显示星期几,使用 %p 显示上午/下午等。

下面是一个带有更具体时间格式的示例:

from datetime import datetime

# 使用now()函数获取当前时间
current_time = datetime.now()

# 格式化输出时间
formatted_time = current_time.strftime("%Y年%m月%d日 %A %p %I:%M:%S")

# 输出格式化后的时间
print("当前时间:", formatted_time)

以上示例将输出类似于 当前时间: 2022年01月01日 Saturday AM 10:30:15 的格式化时间。

通过使用 now() 函数和 strftime() 方法,可以方便地获取当前时间并进行格式化输出,从而满足各种时间展示的需求。