7

I'm trying to parse this datetime string, without success yet, how can I get it?

d = '2014-05-01 18:10:38-04:00'
datetime.datetime.strptime(d,'%Y-%m-%d %H:%M:%S-%Z')

ValueError: time data '2014-05-01 18:10:38-04:00' does not match format '%Y-%m-%d %H:%M:%S%Z'
Goku
  • 1,750
  • 5
  • 23
  • 35
  • 1
    Looking at the docs, %Z only matches things like: (empty), UTC, EST, CST – gknauth May 02 '14 at 13:40
  • %z is supposed to match: (empty), +0000, -0400, +1030. Except %z doesn't work for me when I try strptime ("bad directive, format"). I don't see anything in the docs to handle the TZ format that includes a colon. – gknauth May 02 '14 at 13:44
  • @jonrsharpe The string format isn't the same.. – Goku May 02 '14 at 13:47
  • 1
    from this answer, http://stackoverflow.com/questions/2609259/converting-string-to-datetime-object-in-python it seems "strptime doesn't always support %z". – Padraic Cunningham May 02 '14 at 13:52

2 Answers2

2

You can also use python-dateutil module:

>>> from dateutil import parser
>>> d = '2014-05-01 18:10:38-04:00'
>>> parser.parse(d)
datetime.datetime(2014, 5, 1, 18, 10, 38, tzinfo=tzoffset(None, -14400))

Also see:

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

Did you try iso8601 lib? first install it: https://pypi.python.org/pypi/iso8601/

Then:

    import iso8601
    mydate = '2014-05-01 18:10:38-04:00'
    iso8601.parse_date(mydate)

Out[3]: datetime.datetime(2014, 5, 1, 18, 10, 38, tzinfo=<FixedOffset '-04:00'>)
chespinoza
  • 2,638
  • 1
  • 23
  • 46
  • %timeit iso8601.parse_date(mydate) is 100000 loops, best of 3: 12.3 us per loop VS 71.9 us per loop using python-dateutil, thanks – Goku May 02 '14 at 13:49
  • @Goku oh, nice, `iso8601` is a lot faster, thanks. – alecxe May 02 '14 at 13:56