How to convert string into datetime on Python



Today we're going to learn how to convert a variable from string to datetime. Let's supose we some date like:

Sep 13 2012 11:00PM

If we need to convert this string into a datetime variable for example to store this date into our database in a Django DateField. We have many different ways to do so, here we'll see the most easy and common ways:

Option 1 - Using datetime library

from datetime import datetime
 
date_string = 'Sep 13 2012 11:00PM'
date_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p')
  • %b: Month in short format
  • %d: Day in 2 digit format
  • %Y: Year in 4 digit format
  • %I: Hour in short format (0-12)
  • %M: Minutes in 2 digit format (0-60)
  • %p: AM or PM

To see other formats like day of week, long hour format(0-24), 2 digit year... we can go to the official Python docs with all the possible formats Python: datetime library and formats

Option 2: Using external library dateutil - parser

from dateutil import parser
 
date_string = 'Sep 13 2012 11:00PM'
date_object = parser.parse(date_string)

To install this library we just need to do: pip install dateutil

To read more information about dateutil and parser we should go to Python dateutil

Option 3: Using external library timestring

import timestring

date_string = 'Sep 13 2012 11:00PM'
date_object = timestring.Date(date_string)

To install this library we have to type:  pip install timestring

This library doesn't return a datetime object, it returns a Timestring object, but it's easy to convert between them.

To see more information about Timestring library we should go Github: TimeString

Any doubt don't hesitate commenting !

Leave a comment

You have to wait to comment again. Wait Time: