In today’s quick tutorial we’ll learn how to easily transform string objects to datetime objects.
We’ll look into three main topics:
- Transform a simple string to datetimes.
- Convert a list of strings to a list of datetime objects
- Troubleshooting the module not found strptime error
Strings to date times in Python 3
The function datetime.datetime provides method strptime() which can help us to parse strings that contain date information and transform them into datetime objects.
# define a string object
date_str = '1/14/11'
# convert to datetime
import datetime
my_full_date = datetime.datetime.strptime(date_str,'%m/%d/%y')
my_date = datetime.datetime.strptime(date_str,'%m/%d/%y').date()
my_year = datetime.datetime.strptime(date_str,'%m/%d/%y').year
my_month = datetime.datetime.strptime(date_str,'%m/%d/%y').month
# print the dates, year and month
print("The full date is: " + str(my_full_date))
print("The shortened date is: " + str(my_date))
print("The year is: " + str(my_year))
print("The month is: " + str(my_month))
The result will be:
The full date is: 2011-01-14 00:00:00 The shortened date is: 2011-01-14 The year is: 2011 The month is: 1
Transforming a list of strings to datetime objects
In a similar fashion we can leverage a list comprehension in order to process an entire list of strings and convert them to dates in one go.
# define your list
my_date_list = [ '01/14', '03/17', '04/07', '09/15']
#list comprehension
my_date_list_dt = [datetime.datetime.strptime(date,'%m/%d').date() for date in my_date_list]
# print the list
print(my_date_list_dt)
And here is our result:
[datetime.date(1900, 1, 14), datetime.date(1900, 3, 17), datetime.date(1900, 4, 7), datetime.date(1900, 9, 15)]
Fix the No module found datetime error
I have noted that people often invoke the datetime.strptime() method in the following way:
import datetime
my_full_date = datetime.strptime(date_str,'%m/%d/%y')
This will lead to a modulenotfound error.
The proper way to call the strptime method is as following:
my_full_date = datetime.datetime.strptime(date_str,'%m/%d/%y')
Or alternatively, import the datetime.datetime module:
from datetime import datetime
my_full_date = datetime.strptime(date_str,'%m/%d/%y')