Python Exercise Example 16
**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
(
datetime
.
date
.
today
(
)
.
strftime
(
'
%d/%m/%Y
'
)
)
Create a date object
miyazakiBirthDate
=
datetime
.
date
(
1941
,
1
,
5
)
(
miyazakiBirthDate
.
strftime
(
'
%d/%m/%Y
'
)
)
Date arithmetic
miyazakiBirthNextDay
=
miyazakiBirthDate
datetime
.
timedelta
(
days
=
1
)
(
miyazakiBirthNextDay
.
strftime
(
'
%d/%m/%Y
'
)
)
Date replacement
miyazakiFirstBirthday
=
miyazakiBirthDate
.
replace
(
year
=
miyazakiBirthDate
.
year
1
)
(
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