converting string to a date format

Ben Finney ben+python at benfinney.id.au
Sun Dec 20 21:54:53 EST 2009


tekion <tekion at gmail.com> writes:

> I have this string date format: 24/Nov/2009:10:39:03 -0500 and would
> like to convert it to a date format of "2009-11-24 10:39:03".

This should, ideally, consist of two separate operations:

  * parse the string, using a specific format, to create a ‘datetime’
    object

  * create a string representation of the datetime using your preferred
    string format

> At the moment I am reading datetime module trying to find out if I
> could do it with datetime module.

Unfortunately, the manipulation of time data has historically been a bit
messy in the Python standard library; the functionality for round-trip
conversion of strings and datetime values involves both the ‘datetime’
and ‘time’ modules.

If you have Python 2.6 or greater, you can perform the above steps using
<URL:http://docs.python.org/library/datetime.html#datetime.datetime.strptime>
to parse the string to a ‘datetime’ object, and get a string from the
<URL:http://docs.python.org/library/datetime.html#datetime.datetime.strftime>
method of that object.

If you have an earlier Python, you don't have ‘datetime.strptime’. So
you'll need to follow the hack suggested in the documentation above for
that method, ‘datetime(*(time.strptime(date_string, format)[0:6]))’.

-- 
 \           “Because of the impropriety of entertaining guests of the |
  `\    opposite sex in the bedroom, it is suggested that the lobby be |
_o__)                           used for this purpose.” —hotel, Zurich |
Ben Finney



More information about the Python-list mailing list