Python's datetime module is designed for working with dates and times. It allows various manipulations with time, making it extremely useful in scripts that require real-time data. You can use this module to retrieve the current time from a device, calculate the difference between various time points, or even add a time interval to the current time for a countdown to an event on a website.
One common problem with handling dates and times is their format. For example, in the United States, the format is MM-DD-YYYY, with the month first, then the day, and finally the year. In European countries, the format DD-MM-YYYY is more common. There are also other formats in different regions. Sometimes, in scripts, you need to read and display data in datetime format (date and time). To make this process easier, there are two Python methods to convert strings to datetime objects and back: strptime()
and strftime()
.
In this guide, we'll explore how these methods work in Python and show practical examples of how to use them.
The strptime()
method from the datetime class takes a string as an argument and creates a datetime object. The syntax of the method is as follows:
datetime.strptime(string_date, 'params')
Where:
string_date
: The string from which a datetime object will be created.
params
: Format codes that describe the structure of the date in the string (we'll cover these codes in the "Format Codes" section). These parameters provide information to the method about the date format in the string, whether it's 10.11.2022, 11.10.2022, or 10 November 2022.
Let's look at some example dates in different formats and create new objects from them:
from datetime import datetime as dt
first_strdate = '10.05.2025'
second_strdate = '26-June-2005'
third_strdate = '5 Jan, 11'
first_date = dt.strptime(first_strdate, '%d.%m.%Y')
second_date = dt.strptime(second_strdate, '%d-%B-%Y')
third_date = dt.strptime(third_strdate, '%d %b, %y')
print(first_strdate, '->', first_date)
print(second_strdate, '->', second_date)
print(third_strdate, '->', third_date)
Output:
10.05.2025 -> 2025-05-10 00:00:00
26-June-2005 -> 2005-06-26 00:00:00
5 Jan, 11 -> 2011-01-05 00:00:00
As we can see, the string date can take various formats. The template, which specifies how the string will be converted into a datetime object, is described using format codes and punctuation marks that match the string.
In the first example, the date format is DD.MM.YYYY. To pass this information to the method, we use the following format codes:
%d
: Day of the month as a decimal number.
%m
: Month number.
%Y
: Year with century.
We use the same punctuation in the format string as in the original date string.
The strftime()
method converts a datetime object into a string. The syntax of the method is:
object.strftime("params")
Where:
object
: The datetime object that needs to be converted to a string.
params
: Format codes that define the structure of the resulting string.
Here are a few practical examples of how it works:
from datetime import datetime as dt
time = dt.now()
day_of_the_month = time.strftime("%d")
day_of_the_week = time.strftime("%A")
month = time.strftime("%B")
year = time.strftime("%Y")
format_of_time = time.strftime("%H:%M")
print('Today is', day_of_the_week + '.', 'It is', day_of_the_month, 'day of the', month, year)
print('Current time:', format_of_time)
Output:
Today is Thursday. It is 10 day of the November 2022
Current time: 15:40
Here’s a breakdown of commonly used format codes:
Code |
Description |
Example |
|
Abbreviated weekday name (e.g., Fri for Friday). |
Output: |
|
Full weekday name (e.g., Friday). |
Output: |
|
Abbreviated month name (e.g., Nov for November). |
Output: |
|
Full month name (e.g., November). |
Output: |
|
Date and time (e.g., Fri Nov 11 11:30:00 2022). |
Output:
|
|
Day of the month (01 to 31). |
Output: |
|
Hour in 24-hour format (from 0 to 23). |
Output: |
|
Hour in 12-hour format (from 1 to 12). |
Output: |
|
Day of the year (from 1 to 366). |
Output: |
|
Month number (from 1 to 12). |
Output: |
|
Minutes (from 0 to 59). |
Output: |
|
AM or PM (used with 12-hour format). |
Output: |
|
Seconds (from 00 to 59). |
Output: |
|
Week number of the year (from 0 to 52). The first week starts on Sunday. |
Output: |
|
Day of the week as a number (Sunday is 0, Saturday is 6). |
Output: |
|
Week number of the year (starting with Monday). The first week starts on Monday. |
Output: |
|
Date in MM-DD-YY format. |
Output: |
|
Time in HH:MM format |
Output: |
|
Year without century (from 00 to 99). |
Output: |
|
Year with century. |
Output: |
|
Time zone, if available. |
|
|
Literal % character in the date format. |
Output: |
To work with local date and time formats (e.g., "Diciembre" instead of "December") in Python, you can use locale library:
import locale
locale.setlocale(locale.LC_ALL, 'es_ES')
current_time = datetime.now()
print(current_time.strftime('%A'))
Output:
viernes
In this guide, we've explored how the strptime()
and strftime()
methods work in Python. These are excellent tools for working with dates and times in a flexible and easy way.
If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.