简体   繁体   中英

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?

Your problem is not the timezone, it's the year. You should be using %Y instead of %y :

>>> 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')
>>> date_time_obj
datetime.datetime(2021, 7, 28, 11, 19, 36, 824150, tzinfo=datetime.timezone.utc)

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)

Your problem was that you used %y instead of %Y
(See reference: https://www.programiz.com/python-programming/datetime/strptime )

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM