Advertisement
3th1ca14aX0r

Python datetime objects

Jun 16th, 2024
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | Source Code | 0 0
  1. from datetime import datetime, timedelta
  2.  
  3. # Example 1: Parsing a string into a datetime object
  4. dt_str = "2023-06-16 10:30:45"
  5. dt_obj = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
  6. print("Example 1:", dt_obj)  # Output: Example 1: 2023-06-16 10:30:45
  7.  
  8. # Example 2: Formatting a datetime object into a string
  9. dt_str = dt_obj.strftime("%Y/%m/%d %I:%M %p")
  10. print("Example 2:", dt_str)  # Output: Example 2: 2023/06/16 10:30 AM
  11.  
  12. # Example 3: Performing arithmetic operations on datetime objects
  13. future_dt = dt_obj + timedelta(days=7, hours=3)
  14. print("Example 3:", future_dt)  # Output: Example 3: 2023-06-23 13:30:45
  15.  
  16. past_dt = dt_obj - timedelta(weeks=2, minutes=15)
  17. print("Example 3 (continued):", past_dt)  # Output: Example 3 (continued): 2023-06-02 10:15:45
  18.  
  19. time_diff = future_dt - dt_obj
  20. print("Example 3 (continued):", time_diff)  # Output: Example 3 (continued): 7 days, 3:00:00
  21.  
  22. # Example 4: Comparing datetime objects
  23. dt1 = datetime(2023, 6, 16, 10, 30)
  24. dt2 = datetime(2023, 6, 16, 11, 15)
  25.  
  26. print("Example 4:")
  27. print(dt1 < dt2)  # Output: True
  28. print(dt1 == dt2)  # Output: False
  29. print(dt1 > dt2)  # Output: False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement