16

I'm trying to convert a date string to a datetime object:

dt = datetime.datetime.strptime('2011-07-15 13:00:00+00:00', '%Y-%m-%d %H:%M:%S')

But I'm getting this error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.6/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: +00:00

I guess there is a problem with my format string. How to fix that?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Robert
  • 191
  • 1
  • 2
  • 4
  • 1
    I want to test that the date string is in UTC format or not. So, i guess, ill have to keep the +00:00..right ? – Robert Jul 15 '11 at 13:11
  • You can also use time.strptime and strip the time zone format (and add it later on the datatime processing). – Cinquo Jul 15 '11 at 13:35
  • @Robert I don't think **"UTC format"** means something. I think your datetime string is written in ISO 8601 with UTC offset : see **isoformat([sep])** in the doc. So, I wonder what you want to do. – eyquem Jul 21 '11 at 18:11

3 Answers3

16

How about stripping the offset?

dt_string = '2011-07-15 13:00:00+00:00'
new_dt = dt_string[:19]
dt = datetime.datetime.strptime(new_dt, '%Y-%m-%d %H:%M:%S')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
jcfollower
  • 3,103
  • 19
  • 25
5
dt = datetime.datetime.strptime('2011-07-15 13:00:00+00:00', '%Y-%m-%d %H:%M:%S%z')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Denis
  • 7,127
  • 8
  • 37
  • 58
  • The "%z" format is platform dependent, it seems: [Converting string to datetime object in python](http://stackoverflow.com/questions/2609259/converting-string-to-datetime-object-in-python) – Chris Gregg Jul 15 '11 at 13:21
  • 12
    Should be `%Y-%m-%d %H:%M:%S%z` (notice, no `+` before `%z`). – user443854 Apr 07 '15 at 13:23
-9
>>> datetime.datetime.strptime('2011-07-15 13:00:00', '%Y-%m-%d %H:%M:%S'
datetime.datetime(2011, 7, 15, 13, 0)
Pushpak Dagade
  • 6,280
  • 7
  • 28
  • 41
  • 3
    Doesn't answer the question; you're converting a completely different string to a datetime by dropping the timezone. – Wooble Jul 15 '11 at 13:24