Time Operations

This example demonstrates various time operations in the True-Core time module.

Example Code

Time Operations Example
 1"""
 2Examples of time operations and manipulations using the Time class.
 3"""
 4
 5from true.time import Time, TimeUnit
 6
 7
 8def demo_time_arithmetic():
 9    """Demonstrate time arithmetic operations."""
10    print("=== Time Arithmetic ===")
11
12    time_obj = Time.now()
13    print(f"Current time: {time_obj}")
14
15    # Adding time
16    future = time_obj.add(2, TimeUnit.HOURS)
17    print(f"2 hours later: {future}")
18
19    # Adding days
20    next_week = time_obj.add(7, TimeUnit.DAYS)
21    print(f"Next week: {next_week}")
22
23    # Time difference
24    diff = next_week.difference(time_obj, TimeUnit.HOURS)
25    print(f"Hours between: {diff}")
26
27
28def demo_time_rounding():
29    """Demonstrate time rounding operations."""
30    print("\n=== Time Rounding ===")
31
32    time_obj = Time.now()
33    print(f"Original time: {time_obj}")
34
35    # Round to nearest hour
36    rounded = time_obj.round(TimeUnit.HOURS)
37    print(f"Rounded to hour: {rounded}")
38
39    # Floor to hour
40    floored = time_obj.floor(TimeUnit.HOURS)
41    print(f"Floored to hour: {floored}")
42
43    # Ceil to hour
44    ceiled = time_obj.ceil(TimeUnit.HOURS)
45    print(f"Ceiled to hour: {ceiled}")
46
47
48def demo_time_comparison():
49    """Demonstrate time comparison operations."""
50    print("\n=== Time Comparison ===")
51
52    time1 = Time.now()
53    time2 = time1.add(1, TimeUnit.HOURS)
54
55    print(f"Time 1: {time1}")
56    print(f"Time 2: {time2}")
57
58    print(f"time1 < time2: {time1 < time2}")
59    print(f"time1 == time2: {time1 == time2}")
60    print(f"time1 is between: {time1.is_between(time1, time2)}")
61    print(f"Same day: {time1.is_same(time2, TimeUnit.DAYS)}")
62
63
64def demo_time_ranges():
65    """Demonstrate working with time ranges."""
66    print("\n=== Time Ranges ===")
67
68    time_obj = Time.now()
69
70    # Start and end of day
71    day_start = time_obj.start_of(TimeUnit.DAYS)
72    day_end = time_obj.end_of(TimeUnit.DAYS)
73
74    print(f"Start of day: {day_start}")
75    print(f"End of day: {day_end}")
76
77    # Start and end of month
78    month_start = time_obj.start_of(TimeUnit.MONTHS)
79    month_end = time_obj.end_of(TimeUnit.MONTHS)
80
81    print(f"Start of month: {month_start}")
82    print(f"End of month: {month_end}")
83
84
85if __name__ == "__main__":
86    demo_time_arithmetic()
87    demo_time_rounding()
88    demo_time_comparison()
89    demo_time_ranges()

Key Features

  1. Time Arithmetic - Addition and subtraction - Time scaling - Duration operations

  2. Time Comparison - Equality checking - Ordering operations - Range checking

  3. Advanced Features - Time rounding - Time truncation - Time interpolation