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:
- Importing the datetime from datetime python module using from datetime import datetime.
- We have defined a python string date_str that contains a date in it.
- We have defined a format string format_str that defines the format of date_str.
- Using datetime.strptime() method and passing date_str and format_str to it and it will return the datetime object of the string.
- 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?
Similar Posts
- String to date conversion using Pandas
- Get yesterday date in python
- Get current date in Python (Multiple Formats)
- Convert all string characters to lowercase in python
- Convert JSON string to Python collections - like list, dictionaries
- Convert Python Collections - List, Dict to JSON String
- Convert comma separated string values to tuple python