1

I'm trying to convert a data string that comes from a data set into a datetime object and I am getting the following error,

This error is quite different than others I saw on other questions like Python- strptime ValueError unconverted data remains: :00

import datetime

date_ = '2021-08-31 21:14:39.901557+00'
source_date = datetime.datetime.strptime(date_, '%Y-%m-%d %H:%M:%S.%f')

My error

ValueError: unconverted data remains: +00
The Dan
  • 1,408
  • 6
  • 16
  • 41
  • From what I see `+00` isn't supported. What **is** supported is `+0000` using `%z` as the UTC offset. But `+00` is not a valid UTC offset. Here is the relevant documentation: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior – Bakuriu Jan 28 '22 at 20:03
  • You could do `re.sub(r'([+]\d\d)$', r'\g<1>00', date_)` to ensure that the UTC offset is valid. assuming that when the minutes are missing it is because they are `00` – Bakuriu Jan 28 '22 at 20:12

1 Answers1

2

as @Bakuriu mentioned this is invalid

date_ = '2021-08-31 21:14:39.901557+00'

To fix it you should add the remaining zeros and add a %z to the strptime

date_ = '2021-08-31 21:14:39.901557+0000'
source_date = datetime.datetime.strptime(date_, '%Y-%m-%d %H:%M:%S.%f%z')