Converting string into datetime

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.


  • Python documentation for strptime: Python 2, Python 3

  • Python documentation for strptime/strftime format strings: Python 2, Python 3

  • is also a really nice reference for strftime


  • strptime = “string parse time”
  • strftime = “string format time”
  • Pronounce it out loud today & you won’t have to search for it again in 6 months.

Also, as seen in a comment made by @Izkata, if you want a date instead of a datetime, going through datetime handles it nicely: datetime.strptime(‘Jun 1 2005’, ‘%b %d %Y’).date() == date(2005, 6, 1)

Leave a Comment