joel james
joel james

Reputation: 11

How to convert a time to a string

I am using the date time lib to get the current date. After obtaining the current date I need to convert the obtained date to in to a string format. Any help is appriciated

from datetime import date
today=date.today()
print today

Upvotes: 1

Views: 3751

Answers (4)

GouherDanish
GouherDanish

Reputation: 136

In Python3, you can use f-string formatting:

from datetime import date 
today=date.today()
today_str = f"{today:%m/%d/%y}"
today_str
#>>>'06/24/22'

Upvotes: 1

Gabi Purcaru
Gabi Purcaru

Reputation: 31564

You can use today.strftime(format). format will be a string as described here http://docs.python.org/library/time.html#time.strftime . Example:

from datetime import date
today = date.today()
today.strftime("%x")
#>>> '01/31/11'

Upvotes: 7

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56418

datetime.strftime allows you to format a datetime however you want

Upvotes: 2

PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

stringDate = str(today)

If that's what you want.

Upvotes: 1

Related Questions