13

Im trying to convert a date string to a datetime object as shown below :

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

But,im getting the error below :

Traceback (most recent call last): File "", line 1, in 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 ?

Thank You

Robert
  • 161
  • 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

14

How about ...

    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')
jcfollower
  • 2,991
  • 16
  • 23
4
dt = datetime.datetime.strptime('2011-07-15 13:00:00+00:00', '%Y-%m-%d %H:%M:%S+%z')
Usman Maqbool
  • 3,273
  • 10
  • 31
  • 45
Denis
  • 6,591
  • 6
  • 36
  • 57
  • 3
    Thanks for the reply. The above line gives the error: ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S+%z' – Robert Jul 15 '11 at 13:09
  • 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
  • 8
    Should be `%Y-%m-%d %H:%M:%S%z` (notice, no `+` before `%z`). – user443854 Apr 07 '15 at 13:23
-7
>>> datetime.datetime.strptime('2011-07-15 13:00:00', '%Y-%m-%d %H:%M:%S'
datetime.datetime(2011, 7, 15, 13, 0)
Pushpak Dagade
  • 5,926
  • 7
  • 26
  • 39
  • 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