Python program to convert string to date using datetime module

Python program to convert string to date using datetime module:

In this post, we will learn different ways to convert string to date object in python. This is a common problem that we face in any programming language. We can use third party modules but in this post, we are using inbuilt datetime module.

Using datetime.strptime:

Python provides datetime module to work on time/date related tasks. A lot of different methods are defined in this module that we can use for different time/date conversion in python. For converting one string to date, datetime provides one method called strptime. This method is defined as below :

datetime.strptime(date_str, format)

Here, date_str is the string we are converting to date and format is the format of the date object.

Let’s consider the below example:

from datetime import datetime

date_str = '09-05-20 05:00:00'

date_obj = datetime.strptime(date_str, '%d-%m-%y %H:%M:%S')
print(date_obj)

It will print:

2020-05-09 05:00:00

Format codes for strptime:

Directive Meaning Example
%a Weekday’s as local’s abbreviated name Sun,Mon etc..
%A Weekday’s as local’s full name Sunday, Monday etc…
%w Weekday’s as decimal number from 0(Sunday) to 6(Saturday) 0,1,2…
%d day of month as zero padded number 01, 02, etc..
%b Month as local’s abbreviated name Jan, Feb etc
%B Month in full name January, February etc.
%m Zero padded numbers for months 01,02…
%y Zero padded numbers for year 00, 01, 02 …99
%Y Year as century as decimal 0001, 0002…9999
%H hour in 24 hour as zero padded number 00, 01,…23
%r hour in 12 hour as zero padded number 00, 01…12
%p AM and PM in local AM, PM for enUS or am, pm for deDE
%M zero padded decimal of minute 00,01…59
%S zero padded decimal of second 00,01…59
%f zero padded microsecond decimal number 000000, 000001, …, 999999
%z UTC offset. format is ±HHMM[SS[.ffffff]] +0000 -0400
%Z Time zone name UTC, GMT
%j Day of the year as zero padded decimal 001, 002,…366
%U Weekdays of the year in zero padded decimal. 00, 01…53
%W Week number of the year in zero padded decimal 00, 01,…53
%c Local’s appropriate date and time Tue Jan 14 23:31:00 1990
%x Local’s appropriate date representation 9/12/2020
%X Local’s appropriate time 12:20:00
%% % character %

ValueError and how to deal with this:

strptime() raises one ValueError if we pass any invalid formatter to this method. For example:

from datetime import datetime

date_str = '09-05-20 05:00:00'

date_obj = datetime.strptime(date_str, '%d-%m-%Y %H:%M:%S')
print(date_obj)

I changed the year format to %Y. If you run this, it will throw one ValueError:

raise ValueError("time data %r does not match format %r" %
ValueError: time data '09-05-20 05:00:00' does not match format '%d-%m-%Y %H:%M:%S'

The ideal way to solve this is by using a try-catch block. But make sure to handle it properly in the catch block.

from datetime import datetime

date_str = '09-05-20 05:00:00'

try:
    date_obj = datetime.strptime(date_str, '%d-%m-%Y %H:%M:%S')
except ValueError as e:
    print("Value Error !!")

It will print the message that we are adding in the except block.

Parsing date for a different local:

We can set the local for a date time string and parse it:

from datetime import datetime
import locale

locale.setlocale(locale.LC_ALL, 'de_DE')

date_str = 'Di 16 Jan'

try:
    date_obj = datetime.strptime(date_str, '%a %d %b')
    print(date_obj)
except ValueError as e:
    print("Value Error !!")

You might also like: