user1741339
user1741339

Reputation: 515

Reverse str to datetime.datetime in Python

How do you go about the string '2014-03-16 18:28:11' back to datetime.datetime. I was wondering if there an easier way than the below

>>> 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]

Then use each variable as inputs to datetime.datetime

Upvotes: 1

Views: 1783

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

You want datetime.strptime.

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

Upvotes: 4

Related Questions