Convert String with Month Name to datetime in Python (Example)
In this article, you’ll learn how to convert a string with a month name to a datetime object in Python programming.
The post is structured as follows:
If you want to learn more about these topics, keep reading!
Example Data & Imported Modules
At first, we need to import the datetime module.
from datetime import datetime # Load datetime module
As a next step, we should also create data that we can use later in the example.
s = "15 July 2014" # Sample datetime as string construction
Example: Converting the String with Month Name into datetime by strptime()
By using the strptime() function, we can generate the datetime object with a single line of code.
dt = datetime.strptime(s, "%d %B %Y") # datetime object generation print(dt) # Printing the datetime object # 2014-07-15 00:00:00
The previous output of the Python console shows that our data is successfully converted to a datetime object.
Video & Further Resources
If you need more explanations on the Python code of this page, I recommend watching the following video on my YouTube channel. I show the Python programming syntax of this article in the video.
The YouTube video will be added soon.
In addition, you might want to have a look at the other tutorials on this website. Some other tutorials on similar topics such as dates, data objects, and character strings are below.
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Convert datetime Object to Date Only String in Python
- Convert datetime into String with Milliseconds in Python
- Convert String to datetime Object in Python
- Convert datetime to String without Microsecond Component in Python
- The Python Programming Language
Summary: At this point, you should have learned how to create the datetime of a string with a month name in the Python programming language. In case you have additional questions, don’t hesitate to let me know in the comments section below. Furthermore, please subscribe to my email newsletter for updates on the newest tutorials.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.