converting string to a date format

Ben Finney ben+python at benfinney.id.au
Mon Dec 21 17:05:16 EST 2009


tekion <tekion at gmail.com> writes:

> Ben,
> I do not have python 2.6 install, my version of Python is 2.4.

Ouch :-( Upgrade as soon as possible, 2.4 is no longer receiving bug
fixes <URL:http://www.python.org/download/releases/2.4.6/>.

> So I guess I am stuck on parsing the string "24/Nov/2009:12:00:00
> -0500" using regex and or string function

No, as I suggested, you can use the ‘datetime.datetime’ constructor with
the ‘time.strptime’ output. You only have available the formatting in
<URL:http://docs.python.org/library/time.html#time.strftime>, so the
numeric time zone will be un-parseable by ‘time.strptime’::

    >>> import datetime
    >>> import time
    >>> in_text = "24/Nov/2009:12:00:00 -0500"
    >>> in_time_format = "%d/%b/%Y:%H:%M:%S %Z"
    >>> time.strptime(in_text, in_time_format)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/usr/lib/python2.4/_strptime.py", line 293, in strptime
        raise ValueError("time data did not match format:  data=%s  fmt=%s" %
    ValueError: time data did not match format:  data=24/Nov/2009:12:00:00 -0500  fmt=%d/%b/%Y:%H:%M:%S %Z

Instead you'll need to do as has already been suggested: strip the
numeric time zone and parse the remaining data::

    >>> in_text = "24/Nov/2009:12:00:00 -0500".split(' ', 1)[0]
    >>> in_text
    '24/Nov/2009:12:00:00'
    >>> in_time_format = "%d/%b/%Y:%H:%M:%S"
    >>> time.strptime(in_text, in_time_format)
    (2009, 11, 24, 12, 0, 0, 1, 328, -1)

and use the hack documented in Python 2.6's ‘datetime.datetime.strptime’
function to create a ‘datetime’ object::

    >>> in_time = datetime.datetime(*(time.strptime(in_text, in_time_format)[0:6]))
    >>> in_time
    datetime.datetime(2009, 11, 24, 12, 0)

The benefit of upgrading to Python 2.6 is that you don't need to go
through these contortions with the ‘time’ type's output, you can use the
new ‘datetime.datetime.strptime’ method to get there in one step
<URL:http://docs.python.org/library/datetime.html#datetime.datetime.strptime>.

> to get the output to "2009-11-24 12:00:00".

Once you have a ‘datetime’ object, you can use its ‘strftime’ function
<URL:http://docs.python.org/library/datetime.html#strftime-behavior> to
create a string representation::

    >>> out_time_format = "%Y-%m-%d %H:%M:%S"
    >>> in_time.strftime(out_time_format)
    '2009-11-24 12:00:00'

-- 
 \      “I find the whole business of religion profoundly interesting. |
  `\     But it does mystify me that otherwise intelligent people take |
_o__)                                    it seriously.” —Douglas Adams |
Ben Finney



More information about the Python-list mailing list