datetime object from string

Raymond Hettinger python at rcn.com
Mon Feb 6 20:45:38 EST 2006


Douglas Douglas wrote:
> Hi everybody.
>
> I need to create a datetime object from a string like "20/01/2005 15:10:01". I
> know the mxDateTime module can do this with the DateTimeFrom method, but I was
> wondering if is possible to do this using only the standard library.
>
> I read the datetime object reference but didn't find a method that does it
> directly.
>
> Is it possible to do it with the standard library?

Here's one way:

>>> import time, datetime
>>> s = '20/01/2005 15:10:01'
>>> time_tuple = time.strptime(s, "%d/%m/%Y %H:%M:%S")
>>> datetime.datetime(*time_tuple[:6])
datetime.datetime(2005, 1, 20, 15, 10, 1)

http://docs.python.org/lib/datetime-datetime.html
http://docs.python.org/lib/module-time.html

Raymond




More information about the Python-list mailing list