This article will solve a commonly faced problem to convert a date in string to date object in python and extract various components such as day, month, year, hour, minute, second from  a date in string format with examples.
Python’s datetime module will be used for converting a string to a date which will provide all these components.


Problem
Suppose you have a string such as ‘2020-02-01’  and you want to get year, month and date from it, may be to compare it with some other value or for displaying these values.
One way is to split the string and then get the values but this is not an elegant solution.
Python datetime module
Python’s datetime module provides a datetime class which contains strptime method. This method accepts 2 string arguments.
1. Date to be parsed.
2. Format of the date.
and returns a datetime object.
This object contains different properties that return the components of the date supplied as a string.
Format of the date consist of pre-defined directives and should match the date given in string format. Examples of dates and their corresponding formats is given below,

DateTimeFormat
2020-15-02%Y-%d-%m
2020/02/15%y/%m/%d
15-02-99%d-%m-%y
2020-15-02 11:10:09%Y-%d-%m %H:%M:%S
strptime syntax example

where %Y stands for full year, %y is for year without century, %m is for month, %d is for date, %H, %M and %S stand for hour, month and second respectively.
Above explanation can be easily understood through below illustration.

A complete list of valid directives is given below.

strptime example

Using strptime method to convert a string to date and then extract individual components is given below.

import datetime

date_str = "2020-15-02 11:20:09"
format = "%Y-%d-%m %H:%M:%S"
dt = datetime.datetime.strptime(date_str, format)
print("Type of value returned by strptime:", type(dt))

print("Day:",dt.day)
print("Year:",dt.year)
print("Hour:",dt.hour)
print("Month:",dt.month)
print("Minute:",dt.minute)
print("Second:",dt.second)

Output of above code is

Type of value returned by strptime: <class ‘datetime.datetime’>
Day: 15
Year: 2020
Month: 2
Hour: 11
Minute: 20
Second: 9

Notice the type of object returned by strptime method. It is of type datetime class inside datetime module written as datetime.datetime.
Also, day, year, month, year, hour, minute and second properties of datetime object return the corresponding values of the input date components.

Default datetime value

If you try to print datetime object, then it will print date and time values in default format which is

YYYY-mm-dd HH:MM:SS

Default separator will be “-“. It does not matter if you provide any other separator in your format.
Thus, in above example, if we print the datetime object, then it will print

2020-02-15 11:20:09

If you omit the year, then it will print 1900.
If you omit the month or day, then it will print 01.
If you omit any of the time components, then they will be printed as 00.
These are the default values assumed by datetime method.
01-01-1900 00:00:00 is known as epoch date.

Parsing month in words format

Above example had month in numeric format such as 02. If the string date is of the form “2020-15-Feb”.
format directive in this case will be %b instead of %m. Example,

import datetime

date_str = "2020-15-Feb"
format = "%Y-%d-%b"
dt = datetime.datetime.strptime(date_str, format)
print("Type of value returned by strptime:", type(dt))

print("Day:",dt.day)
print("Year:",dt.year)
print("Month:",dt.month)

Output

Type of value returned by strptime: <class ‘datetime.datetime’>
Day: 15
Year: 2020
Month: 2

Note that the month field returns an integer which is the numeric equivalent of month number such as 1 for January, 2 for February and so on.
If the month name is written in full, such as February, then you need to use %B instead of %b.

Using Invalid date

If the input date contains invalid values according to the format provided, then strptime method raises a ValueError.

For example, if month value is greater than 12 or date is greater than the number of days in the month or the format does not match the input date format etc., then ValueError will be thrown.

import datetime

str = '2020-30-02 11:20:09'

dt = datetime.datetime.strptime(str,'%Y-%d-%m %H:%M:%S')

Above code will throw an error

ValueError: day is out of range for month

since February does not contain 30 days.

import datetime

str = '2020-15-13 11:20:09'

dt=datetime.datetime.strptime(str,'%Y-%d-%m %H:%M:%S')

ValueError: time data ‘2020-15-13 11:20:09’ does not match format ‘%Y-%d-%m %H:%M:%S’

since number of months can not be more than 12.

import datetime

str = '2020-15-13'

dt=datetime.datetime.strptime(str,'%Y/%d/%m')

ValueError: time data ‘2020-15-13’ does not match format ‘%Y/%d/%m’

since the separator between the date and format do not match.

Valid directives list

Following are the most commonly used directives for describing the format of date to strptime method.

DirectiveDescriptionExample
%aShort form for week day.Sun. Mon, Tue
%AFull name for week day.Sunday, Monday
%wWeek day as number from 0 to 6 for Sunday to Saturday respectively.0, 1 etc.
%yYear in 2 digits(without century).99, 00, 20
%YYear in 4 digits(with century).1999, 2000, 2020
%IHour(12 hour clock).12, 01, 05,
%HHour(24 hour clock).00, 01, 22
%mMonth in numeric format. Valid values from 1 to 12.01, 02, 12
%bShort form of month in alphabets.Jan, Feb etc.
%BFull form of month in alphabets.January, February etc.
%dDay of month with valid values from 1 to 31.01, 15 etc.
%MMinutes. Valid value is from 0 to 59.20, 30 etc.
%SSeconds. Valid value is from 0 to 59.25, 55 etc.
%pAM or PM. 
%ZTimezone.UTC, GMT

Hope this article will help you in converting a string to date in python and get its year, month etc., easily.
If you have a format that you are not able to convert, then share it in comments below.

Leave a Reply