Skip to content

timetools Snippets

Joseph Freeston edited this page Apr 13, 2023 · 9 revisions

Timing operations

Note: Remember all times are ultimately stored as their respective unix timestamp/epoch time!

Make sure you've synced time with the server and imported the proper library as per the servercom snippets!

All of these examples assume that somewhere you run sync_time


Getting the current time

from servercom import timetools

# Get the current time
current_time = timetools.Time.now()

# Print the current time
print(current_time)

Calculating elapsed time

from servercom import timetools

# Record the start time
start_time = timetools.Time.now()

# Do something here...

# Record the end time
end_time = timetools.Time.now()

# Calculate the elapsed time
elapsed_time = end_time - start_time

# Print the elapsed time in seconds
print(f"Elapsed time: {int(elapsed_time)} seconds")

# Note: we use int(elapsed_time) to turn the time difference into an integer.
# Using int() on a Time object gives you an integer number of seconds that represents
# that Time object.

Finding the number of minutes past the hour

from servercom import timetools

# Get the current time
current_time = timetools.Time.now()

# Calculate the minutes past the hour
minutes_past_hour = int((current_time % timetools.TimeUnit.HOUR) // timetools.TimeUnit.MINUTE)

# Print the minutes past the hour
print(f"{minutes_past_hour} minutes past the hour")

Calculating the number of minutes left until a given time

from servercom import timetools

# Get the current time
current_time = timetools.Time.now()

# Get a time that represents midnight (00:00 army time) this morning:
midnight = current_time.floor(timetools.TimeUnit.DAY)

# Define the target time
target_time = midnight.offset(hours=13, minutes=30) # 13:30 or 1:30 PM

# Calculate the minutes left until the target time
minutes_left = int((current_time - target_time) // timetools.TimeUnit.MINUTE)

# Print the minutes left until the target time
print(f"{minutes_left} minutes until 13:30 UTC")

Calculating the number of minutes until the next half-hour

from servercom import timetools

# Get the current time
current_time = timetools.Time.now()

# Calculate the minutes past the hour
minutes_past_hour = int((current_time % timetools.TimeUnit.HOUR) // timetools.TimeUnit.MINUTE)

# Calculate the minutes until the next half-hour
minutes_until_half_hour = (30 - minutes_past_hour % 30) % 30

# Print the minutes until the next half-hour
print(f"{minutes_until_half_hour} minutes until the next half-hour")

Going into deep sleep for 30 minutes (See this tutorial)

import alarm
from servercom import timetools

# Get the current time
current_time = timetools.Time.now()

# Represents a time 30 minutes from now:
wake_time = current_time.offset(minutes=30)

time_alarm = alarm.time.TimeAlarm(monotonic_time=wake_time.monotonic)
# Exit the program, and then deep sleep until the alarm wakes us.
alarm.exit_and_deep_sleep_until_alarms(time_alarm)