在 Python 中将 DateTime 转换为带有毫秒的字符串
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
%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
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串