3 April 2019

Examples of time subtraction in Python. Using the best date-time library called Pendulum. You can use add or subtract to alter time.

Source code viewer
  1. import pendulum
  2.  
  3. # Get required timezone.
  4. timezone = pendulum.timezone('Europe/Tallinn')
  5.  
  6. # Get current time in the right timezone.
  7. current_time = pendulum.now(timezone)
  8.  
  9. # Minus one year (-1 year) and apply format you like (https://pendulum.eustace.io/docs/#tokens).
  10. current_time.subtract(years=1).format('DD.MM.YYYY')
  11. # Minus one month (-1 month).
  12. current_time.subtract(months=1)
  13. # Minus six months (-6 months).
  14. current_time.subtract(months=6)
  15. # Minus one day (-1 day).
  16. current_time.subtract(days=1)
  17. # Minus 30 days (-30 days), to get last 30 days for an example.
  18. current_time.subtract(days=30)
  19. # Minus one week (-1 week).
  20. current_time.add(weeks=1)
  21. # Minus one hour (-1 hour).
  22. current_time.subtract(hours=1)
  23. # Minus five minutes (-5 minutes).
  24. current_time.subtract(minutes=5)
  25. # Minus ten seconds (-10 seconds).
  26. current_time.subtract(seconds=10)
  27. # Exact/precise time subscraction.
  28. current_time.subtract(years=1, months=2, days=7, hours=5, minutes=30, seconds=10)
Programming Language: Python