Question 7.2: Formatting Dates You want to convert a date into a string an......

Formatting Dates

You want to convert a date into a string and format it in a certain way.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Apply format string to the date object.

For example:

>>> from datetime import datetime
>>> d = datetime.now()
>>> “{:%Y-%m-%d %H:%M:%S}”.format(d)
‘2013-05-02 16:00:45’
>>>

Discussion

The Python formatting language includes some special symbols for formatting date. %Y, %m, and %d correspond to year, month, and day numbers, respectively.

See Also

See Recipe 7.1 for formatting of numbers.

Formatting in Python actually involves a whole formatting language. You will find full details of this at Python’s website.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...