-1

How should I fix this?

error is:

ValueError: time data '2016-10-20 03:43:11+00:00' does not match format '%Y-%m-%d %H:%M:%S%z'

code is:

fmt = "%Y-%m-%d %H:%M:%S%z"
dt = datetime.strptime(row['Time'], fmt)
Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
  • `+00:00` doesn't match `%z` because it has a colon in it. If you can count on your data always being formatted properly you can do `datetime.strptime(row['Time'][:22] + row['Time'][23:], fmt)`. – Steven Rumbalski Jan 22 '18 at 17:57
  • you could also change your `fmt` as shown below, provided your have constant date formatting. – stucash Jan 22 '18 at 18:04
  • @StevenRumbalski you are right , apologies :) I did a typo in my test code and I just saw it! – stucash Jan 22 '18 at 18:04
  • @stucash: It all depends whether OP's dates have any context that needs to be preserved. There are lots of cases where that time zone doesn't matter. – Steven Rumbalski Jan 22 '18 at 18:05
  • @StevenRumbalski yes, I guess if the date format shown above is what OP wanted to preserve, we could just change the `fmt` and this depends on whether the data has a constant format. – stucash Jan 22 '18 at 18:09

1 Answers1

1

a bit of search would give you some nice solutions.

first option:

from datetime import datetime as dt

t = '2016-10-20 03:43:11+00:00'
fmt = "%Y-%m-%d %H:%M:%S+00:00"
d = dt.strptime(t, fmt)

# output datetime.datetime(2016,10,20,3,43,11)

second option:

from dateutil import parser as psr

t = '2016-10-20 03:43:11+00:00'

d = psr.parse(t)

# output datetime.datetime(2016,10,20,3,43,11, tzinfo=tzutc())
stucash
  • 1,078
  • 1
  • 12
  • 23