在 Python 中将字符串转换为 DateTime 以及将 DateTime 转换为字符串
pythonserver side programmingprogramming更新于 2026/1/22 6:36:17
Python 具有广泛的日期和时间操作功能。在本文中,我们将了解如何将具有正确格式的字符串转换为日期时间以及将日期时间转换为字符串。
使用 strptime
datetime 模块中的 strptime 函数可以通过采用适当的格式说明符将字符串转换为日期时间。
示例
import datetime
dt_str = '2019 年 9 月 19 日 21:02:23 PM'
#给定日期时间
print("给定日期时间:\n",dt_str)
#类型检查
print("数据类型:",type(dt_str))
#格式
dtformat = '%B %d %Y %H:%M:%S %p'
datetime_val = datetime.datetime.strptime(dt_str, dtformat)
print("转换为日期时间后:\n",datetime_val)
#类型检查
print("数据类型:",type(datetime_val))
#恢复为字符串
dtstr_new=str(datetime_val)
print("字符串日期时间",dtstr_new)
print("数据类型:",type(dtstr_new))
输出
运行上述代码得到以下结果 −
给定日期时间: 2019 年 9 月 19 日 21:02:23 PM 数据类型: 转换为日期时间后: 2019-09-19 21:02:23 数据类型: 字符串日期时间 2019-09-19 21:02:23 数据类型:
使用 str
str 函数会将其参数转换为字符串。因此,我们在这里使用 today 函数获取日期时间值,并将其作为参数提供给 str 函数。
示例
import datetime
print("日期时间数据类型:\n",datetime.datetime.today())
print("数据类型:\n",type(datetime.datetime.today()))
dtstr= str(datetime.datetime.today())
print("字符串日期时间:\n",dtstr)
print("数据类型:\n",type(dtstr))
输出
运行上述代码得到以下结果 −
日期时间数据类型: 2020-05-18 11:09:40.986027 数据类型: 字符串日期时间: 2020-05-18 11:09:40.986027 数据类型:
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

