Home > Backend Development > Python Tutorial > How Can I Convert a Date String to a Custom Format Using Python's `datetime` Module?

How Can I Convert a Date String to a Custom Format Using Python's `datetime` Module?

Barbara Streisand
Release: 2024-12-09 12:07:11
Original
274 people have browsed it

How Can I Convert a Date String to a Custom Format Using Python's `datetime` Module?

Converting Date Strings to Custom Formats with Python

Suppose you have a date string like 'Mon Feb 15 2010' and wish to convert it to the format '15/02/2010'. To achieve this, we can leverage Python's datetime module.

The datetime module provides a comprehensive set of tools for manipulating and formatting dates. To parse a date string and change its format, we can use the following approach:

datetime.datetime.strptime(input_date_string, input_format).strftime(output_format)
Copy after login

In this statement, we first parse the input date string input_date_string using the strptime() method, specifying the input_format that describes the original format of the string. This returns a datetime object, which represents the parsed date.

Next, we can use the strftime() method to convert the datetime object to the desired output format. The strftime() method accepts a output_format string, which specifies the format in which the date should be displayed.

For the given example, we can execute the following code:

>>> from datetime import datetime
>>> datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
Copy after login

This code demonstrates how to parse the date string 'Mon Feb 15 2010' from the input format '%a %b %d %Y' and convert it to the output format '%d/%m/%Y', resulting in '15/02/2010'.

The datetime module offers a wide range of format specifiers that can be used to customize the output format of dates. For more information on these specifiers, refer to the Python documentation.

The above is the detailed content of How Can I Convert a Date String to a Custom Format Using Python's `datetime` Module?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template