Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime, timedelta
- # Example 1: Parsing a string into a datetime object
- dt_str = "2023-06-16 10:30:45"
- dt_obj = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
- print("Example 1:", dt_obj) # Output: Example 1: 2023-06-16 10:30:45
- # Example 2: Formatting a datetime object into a string
- dt_str = dt_obj.strftime("%Y/%m/%d %I:%M %p")
- print("Example 2:", dt_str) # Output: Example 2: 2023/06/16 10:30 AM
- # Example 3: Performing arithmetic operations on datetime objects
- future_dt = dt_obj + timedelta(days=7, hours=3)
- print("Example 3:", future_dt) # Output: Example 3: 2023-06-23 13:30:45
- past_dt = dt_obj - timedelta(weeks=2, minutes=15)
- print("Example 3 (continued):", past_dt) # Output: Example 3 (continued): 2023-06-02 10:15:45
- time_diff = future_dt - dt_obj
- print("Example 3 (continued):", time_diff) # Output: Example 3 (continued): 7 days, 3:00:00
- # Example 4: Comparing datetime objects
- dt1 = datetime(2023, 6, 16, 10, 30)
- dt2 = datetime(2023, 6, 16, 11, 15)
- print("Example 4:")
- print(dt1 < dt2) # Output: True
- print(dt1 == dt2) # Output: False
- print(dt1 > dt2) # Output: False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement