Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 how parse a date with format 2014-05-01 18:10:38-04:00 [duplicate]

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'
like image 417
Goku Avatar asked May 02 '14 13:05

Goku


People also ask

How do you parse a date format in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.


2 Answers

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:

  • How to parse dates with -0400 timezone string in Python?
  • How to convert a timezone aware string to datetime in python without dateutil?
like image 142
alecxe Avatar answered Oct 19 '22 04:10

alecxe


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'>)
like image 1
chespinoza Avatar answered Oct 19 '22 03:10

chespinoza