Converting from datetime to string

Use the datetime.strftime() method to convert a Python datetime object to a string of any format.

>>> from datetime import datetime

>>> dt = datetime(2009, 10, 1, 20, 36, 41)
>>> dt.strftime('%d.%m.%Y %H:%M:%S')
'01.10.2009 20:36:41'

The argument to datetime.strftime() is a format string build with format codes. See strftime() and strptime() Format Codes for a list of available format codes.

Converting from string to datetime

Use the datetime.strptime() method to parse a string of any format representing a date and time to a datetime object.

>>> from datetime import datetime

>>> timestamp = '01.10.2009 20:36:41'
>>> datetime.strptime(timestamp, '%d.%m.%Y %H:%M:%S')
datetime.datetime(2009, 10, 1, 20, 36, 41)

The second argument to datetime.strptime() is again a format string (see above).