python

Convert string to date in Python

Python uses the datetime module to convert a string to a date-time format. If you have a string that contains a date and you want to convert it to a date object then you can use the methods explained here.

from datetime import datetime

date_str = '06-06-2021'
format_str = '%m-%d-%Y'
result = datetime.strptime(date_str, format_str)

print(result)

Output

2021-06-06 00:00:00

In the above code snippet:

  1. Importing the datetime from datetime python module using from datetime import datetime.
  2. We have defined a python string date_str that contains a date in it.
  3. We have defined a format string format_str that defines the format of date_str.
  4. Using datetime.strptime() method and passing date_str and format_str to it and it will return the datetime object of the string.
  5. Printing the result.

Format keywords examples

%A - Weekday full name. e.g. Sunday

%a  - Weekday small name. e.g. Sun

%B - Month full name. e.g. February

%b - Month small name. e.g. Feb

%d - Day of the month. e.g. 08

%m - Month as a number. e.g. 8

%Y - Full year in four digits. e.g. 2022

%y - Two-digit year. e.g. 22

More examples of converting date string to date object in different formats

The datetime() function can accept date strings in different formats. Below are some examples that use different formats od date string and then converting then to python date object.

Code Examples

from datetime import datetime

date_str_1 = '8/9/21'
forma_str_1 = '%m/%d/%y'
dt_result_1 = datetime.strptime(date_str_1, forma_str_1)
print(dt_result_1)


date_str_2 = 'Sunday, February 6, 2022'
format_str_2 = '%A, %B %d, %Y'
dt_result_2 = datetime.strptime(date_str_2, format_str_2)
print(dt_result_2)

Output

2021-08-09 00:00:00
2022-02-06 00:00:00
Was this helpful?