3

I'm trying to convert this date '2021-09-29 00:05:00+00:00' into "str" using the following code:

date1 = '2021-09-29 00:05:00+00:00'

date1 = datetime.datetime.strptime(date1,'%Y-%m-%d %H:%M:%S+%f')

but I get the error:

"ValueError: unconverted data remains: :00".

I don't know how to deal with the microseconds. Any help to use strptime with that date format would be more than appreciated!

Thanks in advance.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
AlexRE90
  • 31
  • 2

1 Answers1

2

The +00:00 offset is a timezone offset in hours and minutes. Per the strftime() and strptime() Format Codes documentation, use %z to parse:

Directive Meaning Example Notes
%z UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive) (empty), +0000, -0400, +1030, +063415, -030712.345216 (6)

Syntax for the colon(:) wasn't supported until Python 3.7, per a detail in note 6:

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

from datetime import datetime

s = '2021-09-29 00:05:00+00:00'
t = datetime.strptime(s,'%Y-%m-%d %H:%M:%S%z')
print(t)

Output:

2021-09-29 00:05:00+00:00
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251