-1

I have this DateTime which is a str and I want to convert it into a datetime obj. What is the format?

2021-03-16 04:00:00

Right now I have:

format = 'yyyy-mm-dd mm:ss:ss'

But I am getting this error:

ValueError: time data '2021-03-16 04:00:00' does not match format 'yyyy-mm-dd mm:ss:ss'
svlad
  • 73
  • 8
  • Did you look at the [format string codes](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)? This is not valid format string – buran Mar 19 '21 at 06:24
  • Your format is ISO 8601 compatible, you can simply use [datetime.fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat), e.g. try `datetime.fromisoformat('2021-03-16 04:00:00')`. Besides, check out https://strftime.org/ for a good overview of strptime/strftime formatting/parsing directives. – FObersteiner Mar 19 '21 at 19:53
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Mar 27 '21 at 12:46

1 Answers1

2

You need to use the format %Y-%m-%d %H:%M:%S. Details of the formating can be read from the official documentation

from datetime import datetime


date_str = "2021-03-16 04:00:00"
date_format = "%Y-%m-%d %H:%M:%S"
datetime_object = datetime.strptime(date_str, date_format)
print(datetime_object)

Output:

2021-03-16 04:00:00

Disclaimer

I assume that the hour is 24 hours based.

If the hour value is 12 hours based, then use %Y-%m-%d %I:%M:%S

Reference:

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • Thank you very much for including the documentation! – svlad Mar 19 '21 at 06:35
  • @svlad, you are welcome. If the answer is useful, please mark it as accepted answer. – arshovon Mar 19 '21 at 10:23
  • for such nicely formatted datetime strings, check out [datetime.fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) - it is [more efficient](https://stackoverflow.com/questions/13468126/a-faster-strptime/61710371#61710371) ^^ – FObersteiner Mar 19 '21 at 19:56