How to Format Dates in Python?
When working with dates in Python, it’s important to know how to format them properly. In this article, we will discuss the basics of how to format dates in Python, including different date formatting codes and how to use them.
Python’s built-in datetime
module provides a number of functions and methods for working with dates, including formatting them.
Here are some examples of how to format dates in Python:
Using the strftime() method
The strftime()
method is a commonly used function for formatting dates in Python. It takes a format string as an argument, which specifies how the date should be formatted.
Here’s an example:
from datetime import datetime today = datetime.today() print(today.strftime("%Y-%m-%d"))
Using the strftime() method
The strptime()
method is another useful function for working with dates in Python. It takes a string and a format code as arguments, and returns a datetime object.
Here’s an example:
from datetime import datetime date_string = "2022-01-01" date_object = datetime.strptime(date_string, "%Y-%m-%d") print(date_object)
Using third-party libraries
There are also several third-party libraries available for working with dates in Python, such as dateutil
and arrow
. These libraries provide additional functionality and flexibility for working with dates, including support for time zones and natural language parsing.
Here’s an example using the dateutil
library:
from dateutil.parser import parse date_string = "January 1, 2022" date_object = parse(date_string) print(date_object.strftime("%Y-%m-%d"))