0

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?

1
  • the format is ISO8601 based Commented Nov 18, 2020 at 4:48

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

You can use datetime.fromisoformat, a bit more convenient
@MrFuppes thank you, that's indeed a much cleaner and reliable approach! I've incorporated it to the answer.
oh it's also pretty efficient :) - might be a bit platform-dependent though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.