Python Convert String to Datetime

In this tutorial, we’ll see how to convert string to datetime in python.

When we fetch the value from a textbox while working with GUI in python, by default the value have string datatype.

So here are some ways to convert a string into DateTime.

Python Convert String to Datetime

1. Using datetime library

Lets say our string is ’06-02-2018′

from datetime import datetime
 
date_string = '06-02-2018'
date_object = datetime.strptime(date_string, '%d-%m-%Y')
print(date_object)

Output:

2018-02-06 00:00:00

Where 00:00:00 represents time. In above program, directives

%d = day in 2 digit format

%m = month in 2 digit format

%Y = year in 4 digit format

On other hand if our string is like this  ‘Sep 13 2012 11:00PM’ then we can convert it using this way.

from datetime import datetime
 
date_string = 'Feb 02 2012 08:00PM'
date_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p')
print(date_object)

Output:

2012-02-02 20:00:00

where directives

%b = short form  of month name

%I = hour in short format (0-12)

%M = Minutes in 2 digit format (0-60)

%p = AM or PM

There are many others directives that can be used to convert different types of strings into date. To see more detail on availble directives go to https://docs.python.org/2/library/datetime.html

2. Using external library dateutil – parser

To use this library first we have to install it. To install it, open Terminal or Command prompt and type

‘pip install python-dateutil’

And press enter key. Now we can use this library.

from dateutil import parser
 
date_string = 'feb 06 2018 08:00PM'
date_object = parser.parse(date_string)
print(date_object)

Output:

2018-02-06 20:00:00

Here we don’t need to write directives. For more details about dateutil library please got to http://labix.org/python-dateutil

3. Using external library timestring

Again to use this library we have to install it. To install it open your terminal or command prompt and type

‘pip install timestring’

After installation is done, now we can use this library in our program.

import timestring

date_string = 'feb 06 2018 08:00PM'
date_object = timestring.Date(date_string)
print(date_object)

Output

2018-02-06 20:00:00

Again here we don’t need to write directives. for more detail on timestring library go to https://github.com/stevepeak/timestring

4. Using external library dateparser

To install dateparser, open terminal or command prompt and enter following command.

‘pip install dateparser’

Now we can use it.

import dateparser
date_string = '02/06/2018'
date_object = dateparser.parse(date_string)
print(date_object)

Output

2018-02-06 00:00:00

And if our date string is ‘Fri, 06 feb 2018 08:55:00’ then the program will be same as above, just replace the date_string.

You can ask your queries related to python convert string to datetime.

Leave a Comment

Your email address will not be published. Required fields are marked *