如何在 Python 中从 datetime.now() 获取分钟、秒和毫秒?


在本文中,我们将探讨从 Python 中的 datetime now 获取分钟、秒和毫秒的不同方法。

datetime.now() 方法用于获取当前的分钟、秒和毫秒。这在 datetime 模块中定义。

语法

now() 方法的语法如下:

datetime.now()

返回当前日期和时间,以时间格式表示。

使用 datetime.now() 和 epoctime()

这里我们使用 strftime() 方法,该方法由 datetime 模块提供。我们使用了 datetime.now() 方法来获取当前日期。然后,我们使用 strftime() 方法来格式化此日期。在本例中,我们将格式字符串设置为“分钟:秒.毫秒”的形式。

示例

以下是一个使用 datetime.now() 和 strftime() 方法获取当前分钟、秒和毫秒的示例代码。

from datetime import datetime curr_time = datetime.now() formatted_time = curr_time.strftime('%M:%S.%f') print("Formatted time in Minutes:Seconds:Milliseconds is",formatted_time)

输出

上述示例代码的输出如下:

Formatted time in Minutes:Seconds:Milliseconds is 11:40.325948

使用 datetime.now() 方法检索数据

这里我们使用 datetime.now() 方法获取当前的分钟、秒和毫秒。now() 函数在 datetime 模块中定义。并分别使用 .minute、.second 和 .microsecond 来检索当前的分钟、秒和毫秒。

示例

在下面的示例代码中,我们使用 datetime.now() 方法获取当前的分钟、秒和毫秒。

from datetime import datetime now = datetime.now() print("Today's date is:", now) print("Minutes",now.minute) print("Seconds",now.second) print("Milliseconds",now.microsecond)

输出

上述示例代码的输出如下:

Today's date is: 2022-09-05 10:12:31.476711
Minutes 12
Seconds 31
Milliseconds 476711

更新于:2023年11月2日

17K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.