How to Convert String to Datetime in Python
By
Community /
Developer
Oct 30, 2023
Navigate to:
Converting between text and types related to dates and times is a commonplace task in programming languages, and Python is certainly no exception. That’s why in this post we’ll treat you to a string-to-datetime Python conversion tutorial.
We’ll open the post with a brief overview of the string and datetime types in Python. Python’s dynamically typed nature can be a source of confusion regarding the need for converting between types. That’s why, following the overview, we’ll explain why such conversions are necessary.
With that out of the way, we’ll proceed to give you an introduction to the datetime module in Python. Then, it’s finally time to get practical: We’ll show you how to perform date and time conversions.
Prerequisites
Do you want to follow along with the post? For that, you’ll need to have Python 3.x installed and be at least familiar with the language.
String and Datetime: Overview
Let’s first get something out of the way: In Python, (almost) everything’s an object. So, unlike other major programming languages, Python doesn’t have the notion of primitive types as a different kind of artifact. Things like numbers, dates, and strings are objects in the same sense that the objects instantiated from the classes you create are.
First, let’s cover strings. According to Python’s documentation: “Strings are immutable sequences of Unicode code points.” Strings are represented by the str type.
The datetime module contains several types related to handling time and dates. An important characteristic of date and time in Python is the concept of naive and aware objects. Naive objects are ones that don’t have any notion of timezones. They’re simply dates/times not bound to any particular zone.
Aware objects, on the other hand, do have timezone information.
Why the String-to-Datetime Python Conversion Matters
You’re probably aware of the fact that Python has dynamic typing, which means that the types of variables aren’t written in stone at the time of development. You can, for instance, assign a string to a variable right after assigning a number to it:
value = "Some text"
print(type(value))
value = 10
print(type(value))
Another important consequence of dynamic typing is that you can pass values from any type as arguments to functions, even if you use type hints. With that in mind, a beginner would be forgiven for asking what’s the point of performing a conversion from string to a datetime after all. Couldn’t you just have the dates as strings? There are many reasons why such conversions make sense:
-
Correctness. There’s a plethora of date formats in use around the world. Having dates as strings, especially in programs that need to be localized can potentially generate bugs and maintenance difficulties.
-
Performance. Datetime objects are created for handling date concerns in the most optimal way, which means opting for strings can cause your application’s performance to suffer.
-
Code quality. There are methods and functions that operate on datetime objects that offer features related to time. If you store dates in strings, you wouldn’t have access to those and would have to code them yourself, opening the possibility for bugs and generating more code that has to be tested, maintained, and documented.
Regarding that last point, here’s how you’d go about adding days to a date:
from datetime import datetime, date, timedelta
today = datetime.today()
dayAfterTomorrow = today + timedelta(days=1)
print(dayAfterTomorrow)
In short, if you opted not to use datetime and its companion types, you’d end up creating less-performant, less-safe, and less-maintainable replacements for them.
The Datetime Module in Python: Introduction
As you’ve seen, the datetime module in Python is the one you use to handle date and time concerns. It contains several classes, but these are the main ones:
- date: contains only date information, without time of day, and it’s a naive object
- time: contains only time information, without being bound to any specific day
- datetime: a combination of date, time, and timezone (i.e., an aware type)
- tzinfo: contains timezone information
For more information on the datetime module, refer to the official documentation.
String to Datetime Python Conversion: Hands-On Tutorial
Up until now, we’ve covered:
- the string and datetime types in Python
- why converting from string to datetime is important
- what the datetime module is in Python and what it contains
With those fundamentals out of the way, let’s get to the practical part of the post.
How Can I Convert a String to a Datetime Object in Python?
Let’s start by covering the most basic scenario first. Suppose you have a string containing a date in the ISO-8601 format:
today = "2023-08-26"
To start the conversion, first you have to import the datetime module. Since what we have is simply a date without a time, you’ll import just the date object:
from datetime import date
To perform the conversion, you’ll use the fromisoformat class method on the datetime class:
today_object = date.fromisoformat(today)
To ensure the conversion works, you can print the type of the new object. The complete code now looks like this:
from datetime import date
today = "2023-08-26"
today_object = date.fromisoformat(today)
print('Type of string variable:',type(today))
print('Type of date variable:',type(today_object))
You’ll not always be so lucky as to have your dates in ISO format. As said earlier, there are many different formats for dates available. The following example converts a string to a date object, considering the date is in the dd/mm/yyyy format:
Type of string variable: <class 'str'>
Type of date variable: <class 'datetime.date'>
You’ll not always be so lucky as to have your dates in ISO format. As said earlier, there are many different formats for dates available. The following example converts a string to a date object, considering the date is in the dd/mm/yyyy format:
from datetime import datetime
date_string = "26/08/2023"
date_format = "%d/%m/%Y"
date_object = datetime.strptime(date_string, date_format).date()
print('Type of resulting object:', type(date_object))
print(date_object)
There are several interesting things in the code above:
- Notice we define the format using a string.
- This time, we used the strptime method to convert the string, supplying the format we defined earlier as the second argument.
- The strptime method returns a datetime object, on which we call the date() method to obtain an object that has only the date component.
By running the code above, you’ll see the following result:
Type of resulting object: <class 'datetime.date'>
2023-08-26
Also notice that, when we pass the date object for the print function, it uses the ISO-8601 format as the default formatting.
What Modules or Packages Are Required for Converting Strings to Datetime in Python?
Up until now, we converted strings to date objects. Let’s now convert them to datetime objects.
The first step is to make sure you’re importing the datetime type from the datetime module, like this:
from datetime import datetime
Then, let’s define a date and a format, exactly like in the previous example:
date_string = "26/08/2023"
date_format = "%d/%m/%Y"
This is where things change. We’ll convert like before, but without calling the date() method at the end:
date_object = datetime.strptime(date_string, date_format)
print('Type of resulting object:', type(date_object))
print(date_object)
Now, after running the script, this is what we get:
Type of resulting object: <class 'datetime.datetime'<
2023-08-26 00:00:00
As you can see, the resulting type is now datetime instead of just date. Also, since the input string didn’t contain any time, the print() function displays all zeroes for the time portion.
How Can I Handle Different Date and Time Formats When Converting Strings to Datetime in Python?
As you’ve seen, the strptime method accepts a string as a second argument, which refers to the format for the input date. What happens, though, if the string provided doesn’t match the pattern? Well, an error ensues. Of course, in a real-world application, you have to account for that possibility. The following example showcases how to test an input string for several different format possibilities, and handle the error if none of the formats match:
from datetime import datetime
date_string = "26/08/2023 18:14:00"
possible_formats = [
"%d/%m/%Y %H:%M:%S",
"%Y-%m-%d %H:%M:%S",
"%m/%d/%Y %H:%M:%S",
"%d/%m/%Y",
"%Y-%m-%d"
]
parsed_datetime = None
for date_format in possible_formats:
try:
parsed_datetime = datetime.strptime(date_string, date_format)
break
except ValueError:
pass
if parsed_datetime is not None:
print("Parsed datetime:", parsed_datetime)
else:
print("Unable to parse datetime with any of the formats")
Conclusion
Python is known, among other things, for being quite an approachable language. Its simplicity makes it a great first language, for instance. This simplicity certainly shows when it comes to handling date and time concerns: just import the datetime module, and you have all the types you need at your disposal.
In this post, we’ve treated you to an introduction to datetime in Python. You’ve learned why converting from string to datetime is important and learned how doing it is a walk in the park. However, we’ve just scratched the surface when it comes to all of the date/time features that Python has to offer. As a next step, continue exploring Python’s docs, learning about date, time, datetime, and all of the other types available. You can also check out some of the following resources:
This post was written by Carlos Schults. Carlos is a consultant and software engineer with experience in desktop, web, and mobile development. Though his primary language is C#, he has experience with a number of languages and platforms. His main interests include automated testing, version control, and code quality.