Python Practice Example 16
Problem:Output the date in a 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 operations
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/1942Other extensions
Python 100 Examples