-1

Problem: I have the following string '2021-03-10T09:58:17.027323+00:00' which I want to convert to datetime. I have difficulties with the format. This is what I tried so far:

datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.z")

Any help is highly appreciated!

rkraft
  • 495
  • 4
  • 16
  • 1
    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 10 '21 at 10:09

2 Answers2

1

The correct format string is "%Y-%m-%dT%H:%M:%S.%f%z"

>>> from datetime import datetime
>>> datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2021-03-10T09:58:17.027323+00:00')
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)

But as mentioned in the comments - better use fromisoformat()

buran
  • 13,682
  • 10
  • 36
  • 61
0

Given that your string is known from before and you won't be using a now time feature, you can check here I think you can use the following code:

   import datetime

   date_time_str = '2018-06-29 08:15:27.243860'
   date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
   
   print('Date:', date_time_obj.date())
   print('Time:', date_time_obj.time())
   print('Date-time:', date_time_obj)
Spiros
  • 99
  • 10