如何将字符串转换为datetime.datetime对象?

时间:2019-11-08 01:32:58

标签: python python-3.x date datetime python-datetime

我将此日期作为字符串birthday = "2000-01-23 00:00:00"

如何将其变成datetime.datetime对象,所以当我打印birthday时它会打印出datetime.datetime(2000, 1, 23, 0, 0)

birthday = "2000-01-23 00:00:00"
# birthday = datetime object
print(birthday)

4 个答案:

答案 0 :(得分:0)

您可以像这样使用strptime

import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

答案 1 :(得分:0)

您可以使用第三方 dateutil 库:

您可以通过以下方式安装它:

pip install python-dateutil


from dateutil import parser
parser.parse("2000-01-23 00:00:00")  # datetime.datetime(2000, 1, 23, 0, 0)

答案 2 :(得分:0)

这就是我要做的:

datetime =datetime.strptime(birthday, "%Y-%m-%d %H:%M:%S")

答案 3 :(得分:0)

尝试:

from datetime import datetime

birthday = "2000-01-23 00:00:00"

birthday_object = datetime.strptime(birthday, '%Y-%m/%d %H:%M:%S')

此外,我建议您看看official documentation