Sunday, January 19, 2025
HomeQ&AHow do I Convert date time object to a String of date...

How do I Convert date time object to a String of date only in Python?

To convert a datetime object to a string of date only in Python, you can use the strftime method.

Here’s an example:

from datetime import datetime

Create a datetime object
dt = datetime.now

Convert datetime object to a string of date only
date_str = dt.strftime(‘%Y-%m-%d’)

print(date_str)

In this example, ‘%Y-%m-%d’ is the format code for the date string. Here’s what each part of the code means:

See also  Python Functions

– %Y: Four-digit year
– %m: Two-digit month (01-12)
– %d: Two-digit day of the month (00-31)

You can adjust the format code to suit your needs.

Alternatively, you can use the date method to get the date part of the datetime object, and then convert it to a string using the isoformat method:

See also  Does the Cuban and Puerto Rican flags share same design?

date_str = dt.date().isoformat()

This will also give you a string in the format YYYY-MM-DD.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x