How to Convert a String to a Date in Python
Table of Contents
Working with dates and time is one of the most useful things to do in Python.
When working with dates, sometimes you are only given a string and you need to convert it to a date object.
In this post, we will look at how to convert a string to a date in Python.
How to convert a string to a date
Let's say we have a string that we want to convert to a date.
PYTHONdate_string = "2022-01-01"
We can use the datetime
module to convert the string to a date by using the built-in strptime
function.
We just pass in the raw string and the format of the string so that it can be parsed.
PYTHONfrom datetime import datetime
date_string = "2022-01-01"
date = datetime.strptime(date_string, "%Y-%m-%d")
Now you can confirm that it worked by printing the type of the date and the date itself:
PYTHONfrom datetime import datetime
date_string = "2022-01-01"
date = datetime.strptime(date_string, "%Y-%m-%d")
print(type(date))
print(date)
BASH<class 'datetime.datetime'>
2022-01-01 00:00:00
Conclusion
In this post, we learned how to convert a string to a date in Python.
Simply import the datetime
module and pass in the string and format of it, and it will take care of the rest for you.
Thanks for reading and happy coding!
- Getting Started with Solid
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js