Reputation: 672
Say I have a datetime string created form a datetime input in html as:
"2020-11-27T16:18"
How would I convert this to a datetime object in python:
string_date = "2020-11-27T16:18"
datetime_object = ????
Is there a specific way to format this date into a datetime object in python?
Upvotes: 0
Views: 487
Reputation: 7538
Here how to do it using datetime.strptime
:
>>> import datetime
>>>
>>> datetime.datetime.strptime(string_date, '%Y-%m-%dT%H:%M')
datetime.datetime(2020, 11, 27, 16, 18)
Or a more convenient and clean solution as pointed out by @MrFuppes is to use datetime.fromisoformat
>>> from datetime import datetime
>>> string_date = "2020-11-27T16:18"
>>> datetime.fromisoformat(string_date)
datetime.datetime(2020, 11, 27, 16, 18)
Upvotes: 3