In this post, you’ll learn how to convert a Python string to a date, using the datetime
module’s .strptime[]
method. Specifically, you’ll learn how to convert a string to a date and how to convert a Pandas column to datetime with this approach.
Working with dates, times, and timezones is a problem often faced in software development. The dates and times you receive back may not always be in a datetime format. It then becomes important to convert them.
The
Quick Answer: Use Datetime’s strptime
function
from datetime import datetime date_string = '2021-12-31' datetime = datetime.strptime[date_string, '%Y-%m-%d'] print[datetime] # Returns: 2021-12-31 00:00:00
Let’s dive in!
- Python Datetime Strptime: What is it?
- How do you convert Python String to Date?
- What are Datetime’s Format Codes?
- Convert a Pandas column to datetime with strptime
- Conclusion
Python Datetime Strptime: What is it?
Python’s datetime
module comes built into your Python installation, meaning you don’t need to worry about installing it.
The datetime
module comes with three main object types: date
, time
,
and datetime
. They can be considered self-explanatory, but just in case: date
deals with dates, time
deals with times, and datetime
deals with both dates and times.
One of the very helpful methods that we can use within the datetime
module is the strptime
method that allows us to convert a string
to a date
[or in our case, a datetime
].
The method looks like this:
datetime.strptime[date_string=, format=]
- The
date_string
is the string that holds what we want to convert. - the
format
contains the format of the string. Learn more about it in the section on format code examples below.
How do you convert Python String to Date?
In order to convert a Python string to a date [or datetime], we can use the datetime .strptime[]
method.
Let’s see how we can do this:
- We import the
datetime
object from thedatetime
module - We pass the string into the
.strptime[]
method, as well as its format - We assign this to a new variable and print it out
from datetime import datetime date_string = '2021-12-31 15:37' datetime = datetime.strptime[date_string, '%Y-%m-%d %H:%M'] print[datetime] # Returns: 2021-12-31 15:37:00
At first glance, these format codes may look a little funny. You’ll learn all about some different examples in the next section.
What are Datetime’s Format Codes?
The datetime
module uses a specific format codes in order to convert a string to a datetime or a datetime to a string. In the list below, you’ll learn a number of the most important format codes
that you’ll encounter:
%a
: Weekday in the locale’s abbreviated name [e.g., Mon]%A
: Weekday in the locale’s full name [e.g., Monday]%b
: month as locale’s abbreviated name [e.g., Dec]%B
: month as locale’s full name [e.g., December]%m
: month as zero-padded decimal number [e.g., 01]%d
: day as a zero-padded decimal number [e.g., 09]%y
: year without century [e.g., 2021]%Y
: year with century [e.g., 21]
For example, if you’re given a string that looks like this: 'Monday June 3, 2021'
, you’d write '%A %B %d, %Y'
The important thing to know here is that characters like commas or colons need to be included as well. This may feel a bit unnatural but think of the format codes as placeholders.
To see the rest of the format codes, check out the official documentation here.
Convert a Pandas column to datetime with strptime
Pandas has a very helpful built-in tool called .to_datetime[]
to convert a column to, well, datetime. You can learn about it in details in this post here.
Let’s load this dataframe and see what it looks like:
import pandas as pd df = pd.DataFrame.from_dict[ { 'Name': ['Jane', 'Melissa', 'John', 'Matt'], 'Hire Date': ['2021-03-13', '2019-01-01', '2018-04-12', '2016-12-12'], 'Gender': ['F', 'F', 'M', 'M'] } ] print[df]
This returns:
Name Hire Date Gender 0 Jane 2021-03-13 F 1 Melissa 2019-01-01 F 2 John 2018-04-12 M 3 Matt 2016-12-12 M
Now, let’s use
the method to convert the Hire Date
column to datetime:
df['Hire Date'] = pd.to_datetime[df['Hire Date']]
However, if you wanted to use the datetime .strptime
method, you could apply the function to the entire column. Keep in mind, this isn’t efficient and the Pandas .to_datetime[]
method is much more efficient. Learn a bit more about the Pandas .apply[]
method in my post here.
df['Hire Date'] = df['Hire Date'].apply[lambda x: datetime.strptime[x, '%Y-%m-%d']]
Conclusion
In this post, you learned how to convert a Python string to date or datetime. You learned how the datetime strptime function works, what datetime format codes are, as well as how to handle string to date conversion in Pandas.
To learn more about the datetime strptime function, check out the official documentation here.