Python - Date - Basics


/ Published in: Python
Save to your folder(s)

Reference of simple operations with dates, such as formatting and arithmetic.


Copy this code and paste it in your HTML
  1. import datetime
  2.  
  3. if __name__ == '__main__':
  4.  
  5. # printing today's date formatted as dd/mm/yyyy. For more formatting options, search for strftime() in Python documentation
  6. print(datetime.date.today().strftime('%d/%m/%Y'))
  7.  
  8. # creating a date object
  9. miyazakiBirthDate = datetime.date(1941, 1, 5)
  10.  
  11. print(miyazakiBirthDate.strftime('%d/%m/%Y'))
  12.  
  13. # example of date arithmetic operation. Adding one day to miyazakiBirthDate
  14. miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1)
  15.  
  16. print(miyazakiBirthNextDay.strftime('%d/%m/%Y'))
  17.  
  18. # example of date part replacement. Changing the miyazakiBirthDate year to year + 1
  19. miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1)
  20.  
  21. print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.