Home > Backend Development > Python Tutorial > How to Convert a Python Datetime Object to a Date-Only String?

How to Convert a Python Datetime Object to a Date-Only String?

Susan Sarandon
Release: 2024-11-16 00:09:03
Original
939 people have browsed it

How to Convert a Python Datetime Object to a Date-Only String?

Converting Datetime Objects to Date-Only Strings in Python

In Python, it's common to encounter situations where you need to convert a datetime object into a string representing only the date. For instance, you may have a datetime object like:

datetime.datetime(2012, 2, 23, 0, 0)
Copy after login

And you want to transform it into a string like '2/23/2012'. To achieve this, the strftime method proves to be a valuable tool.

The strftime method allows you to format your datetime object into a desired string representation. Here's an example to demonstrate its usage:

import datetime

t = datetime.datetime(2012, 2, 23, 0, 0)
date_string = t.strftime('%m/%d/%Y')
Copy after login

In this example, we've used the '%m/%d/%Y' format string. It specifies the output format as follows:

  • '%m': Month as a two-digit number (01-12)
  • '%d': Day of the month as a two-digit number (01-31)
  • '%Y': Year with century as a four-digit number (e.g., 2012)

As a result, running the above code will produce the desired date-only string:

'02/23/2012'
Copy after login

For further customization options, you can refer to the extensive documentation provided by the Python library on formatting date and time.

The above is the detailed content of How to Convert a Python Datetime Object to a Date-Only String?. 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