Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 16

Python Exercise Example 16

Python 100 Examples Python 100 Examples

**Question:** Output a date in the specified format.

**Program analysis:** Use the datetime module.

Example

#!/usr/bin/python

-- coding: UTF-8 --

import

datetime

if

name

==

'

main

'

:

Output today's date in the format dd/mm/yyyy. For more options, see the strftime() method

print

(

datetime

.

date

.

today

(

)

.

strftime

(

'

%d/%m/%Y

'

)

)

Create a date object

miyazakiBirthDate

=

datetime

.

date

(

1941

,

1

,

5

)

print

(

miyazakiBirthDate

.

strftime

(

'

%d/%m/%Y

'

)

)

Date arithmetic

miyazakiBirthNextDay

=

miyazakiBirthDate

datetime

.

timedelta

(

days

=

1

)

print

(

miyazakiBirthNextDay

.

strftime

(

'

%d/%m/%Y

'

)

)

Date replacement

miyazakiFirstBirthday

=

miyazakiBirthDate

.

replace

(

year

=

miyazakiBirthDate

.

year

1

)

print

(

miyazakiFirstBirthday

.

strftime

(

'

%d/%m/%Y

'

)

)

The output of the above example is:


27/04/2021
05/01/1941
06/01/1941
05/01/1942

Python 100 Examples Python 100 Examples