Python comes with the datetime library to manipulate date and times. One of the most common manipulation we want to achieve is to convert a string representing a date to a real date object. By doing so, we’d be able to calculate the difference between two dates, for instance.
One thing I’d like to highlight before starting this tutorial is that the code may be different based on how you import the datetime library. You often have two options:
#option 1
import datetime
#option
from datetime import datetime
Code language: Python (python)
The first option will load the whole datetime library and if you want to refer to the datetime object inside the datetime library, you’ll have to use datetime.datetime. The second option loads only the datetime object and you can use datetime directly. In this tutorial, I’ll use the second option.
Table of Contents
Convert a string to a date using strptime() method
If you need to convert a string to a datetime object in Python, you must use the strptime() method. It is a built-in method from the datetime object to return a datetime object from a string. Let’see a simple example:
from datetime import datetime
date_str = '30/01/2022'
date = datetime.strptime(date_str, '%d/%m/%Y')
print(date)
Code language: Python (python)
Output:
2022-01-30 00:00:00
Code language: CSS (css)
One thing that you may not understand is the second parameters used in the strptime() method. It is used to identify the date format used in our string.
from datetime import datetime
date_str = '30/01/2022'
date = datetime.strptime(date_str, '%d/%m/%Y')
print(date)
Code language: JavaScript (javascript)
The documentation is pretty clear about what you can use to help Python understand your date format. You may not need the majority of them in most cases, though.
Directive | Meaning | Example |
---|---|---|
%a | Weekday as locale’s abbreviated name. | Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE) |
%A | Weekday as locale’s full name. | Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE) |
%w | Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. | 0, 1, …, 6 |
%d | Day of the month as a zero-padded decimal number. | 01, 02, …, 31 |
%b | Month as locale’s abbreviated name. | Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE) |
%B | Month as locale’s full name. | January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE) |
%m | Month as a zero-padded decimal number. | 01, 02, …, 12 |
%y | Year without century as a zero-padded decimal number. | 00, 01, …, 99 |
%Y | Year with century as a decimal number. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 00, 01, …, 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, …, 12 |
%p | Locale’s equivalent of either AM or PM. | AM, PM (en_US);am, pm (de_DE) |
%M | Minute as a zero-padded decimal number. | 00, 01, …, 59 |
%S | Second as a zero-padded decimal number. | 00, 01, …, 59 |
%f | Microsecond as a decimal number, zero-padded to 6 digits. | 000000, 000001, …, 999999 |
%z | UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive). | (empty), +0000, -0400, +1030, +063415, -030712.345216 |
%Z | Time zone name (empty string if the object is naive). | (empty), UTC, GMT |
%j | Day of the year as a zero-padded decimal number. | 001, 002, …, 366 |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, …, 53 |
%W | Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, …, 53 |
%c | Locale’s appropriate date and time representation. | Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE) |
%x | Locale’s appropriate date representation. | 08/16/88 (None);08/16/1988 (en_US);16.08.1988 (de_DE) |
%X | Locale’s appropriate time representation. | 21:30:00 (en_US);21:30:00 (de_DE) |
%% | A literal '%' character. | % |
Why is it useful to convert a string to a date?
One of the main advantages of converting a string to a datetime object is that we can access its attributes. By default, the available attributes are: year, month, day, hour, minute, second, microsecond and tzinfo. Let’s try to get the day number from a random date, for instance:
from datetime import datetime
date_str = '30/01/2022'
date = datetime.strptime(date_str, '%d/%m/%Y')
print(date.day)
Code language: Python (python)
Output:
30
The result may seem obvious in this case, but the ability to extract the date from a string can allow us to analyze datasets and create daily averages, for example. You can also combine the strptime() and strftime() methods to extract the day name from a date:
from datetime import datetime
date_str = '30/01/2022'
date = datetime.strptime(date_str, '%d/%m/%Y')
print(date.strftime('%a'))
Code language: Python (python)
Output:
Sun