在 Python 中将 DateTime 转换为带有毫秒的字符串

您所在的位置:网站首页 71620002毫秒 在 Python 中将 DateTime 转换为带有毫秒的字符串

在 Python 中将 DateTime 转换为带有毫秒的字符串

#在 Python 中将 DateTime 转换为带有毫秒的字符串 | 来源: 网络整理| 查看: 265

使用 strftime() 方法将 DateTime 格式化为字符串 使用 isoformat() 方法将 DateTime 格式化为字符串 使用 str() 函数将日期时间格式化为字符串

Python 中的 datetime 模块允许我们创建日期和时间对象,很容易操作和转换为不同的格式。

本教程将介绍如何将 datetime 对象转换为包含毫秒的字符串。

使用 strftime() 方法将 DateTime 格式化为字符串

strftime() 方法根据参数中指定为字符串的特定格式返回一个字符串。

from datetime import datetime date_s = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") print(date_s)

输出:

2021-01-23 02:54:59.963001 注意 如果我们只导入 datetime,我们将不得不使用 datetime.datetime.now() 来获取当前的日期时间。

%Y-%m-%d %H:%M:%S.%f 是字符串格式。now() 方法返回当前日期和时间的 datetime.datetime 对象。注意,最后输出的微秒,可以很容易地截断为毫秒。例如:

from datetime import datetime date_s = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] print(date_s)

输出:

2021-01-23 03:00:29.052 使用 isoformat() 方法将 DateTime 格式化为字符串

datetime 类的 isoformat() 方法返回一个以 ISO 8601 格式表示日期的字符串。我们可以使用 sep 参数和 timespace 参数指定分隔日期和时间的字符为' ',该参数确定时间部分为毫秒。

from datetime import datetime date_s = datetime.now().isoformat(sep=" ", timespec="milliseconds") print(date_s)

输出:

2021-01-23 03:15:35.322 使用 str() 函数将日期时间格式化为字符串

我们可以直接将 datetime 对象传递给 str() 函数,得到标准日期和时间格式的字符串。这种方法比上面的方法要快,但是我们可以指定字符串的格式。

我们也可以简单地从字符串中去掉最后三位数字,得到以毫秒为单位的最终结果。

from datetime import datetime t = datetime.now() date_s = str(t)[:-3] print(date_s)

输出:

2021-01-23 05:56:26.266


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3