Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with +00:00 to datetime in Python

I am stuck on how to convert this strong to a datetime object. This is what I tried:

import datetime
date_time_str = "2021-07-28 11:19:36.824150+00:00"
date_time_obj = datetime.datetime.strptime(date_time_str, '%y-%m-%d %H:%M:%S.%f%z')

However, I keep getting the

ValueError: time data '2021-07-28 11:19:36.824150+00:00' does not match format.

What is the correct format?

like image 522
Branco François Avatar asked Oct 26 '25 09:10

Branco François


1 Answers

Regarding the doc

  • %y is for 2 digit year
  • %Y is for 4 digit year

Use '%Y-%m-%d %H:%M:%S.%f%z'

date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f%z')

Or use fromisoformat

date_time_obj = datetime.fromisoformat(date_time_str)
like image 165
azro Avatar answered Oct 27 '25 21:10

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!