在Python中将str反转到datetime.datetime

时间:2014-07-24 12:59:03

标签: python datetime

你怎么去字符串'2014-03-16 18:28:11'回到datetime.datetime。我想知道是否有比下面更简单的方法

>>> datetime.datetime(2014, 3, 16, 18, 28, 11)
>>> str(datetime.datetime(2014, 3, 16, 18, 28, 11))
'2014-03-16 18:28:11'
>>> complete = str(datetime.datetime(2014, 3, 16, 18, 28, 11))
>>> date, time = complete.split(" ")
>>> [int(x) for x in date.split("-")]
[2014, 3, 16]
>>> [int(x) for x in time.split(":")]
[18, 28, 11]

然后使用每个变量作为datetime.datetime的输入

1 个答案:

答案 0 :(得分:3)

您想要datetime.strptime

date = datetime.datetime.strptime(complete, '%Y-%m-%d %H:%M:%S')