MEOS/Utilities/Time.py

55 lines
2.0 KiB
Python

import time
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as pl
def get_current_time():
"""Returns the current time in seconds since the epoch."""
return time.time()
def generate_timestrings(start_time_str, end_time_str, dt):
"""Generates a list of timestamps from start_time to end_time, which are strings such
as 19:00."""
timestamps = []
current_time = datetime.strptime(start_time_str, "%H:%M")
end_time = datetime.strptime(end_time_str, "%H:%M")
while current_time <= end_time:
timestamps.append(current_time)
current_time += timedelta(seconds=dt)
timestrings = [dt.strftime("%H:%M") for dt in timestamps]
return timestrings
def index_peak_times(timestamps, peak_times, peak_durations):
"""Converts peak times from HH:MM format to seconds since epoch."""
# start_time is the start time of the batch process in seconds since the epoch
# peak_times is a list of strings in HH:MM format
dt = timestamps[1] - timestamps[0] # time step in seconds
peak_indices = np.zeros(len(timestamps), dtype=int)
start_datetime = datetime.fromtimestamp(timestamps[0])
processed_times = []
peak_occurence_no = 1
for time_str, duration in zip(peak_times, peak_durations):
# convert HH:MM to a datetime object
time_obj = datetime.strptime(time_str, "%H:%M")
full_datetime = start_datetime.replace(
hour=time_obj.hour, minute=time_obj.minute, second=0, microsecond=0
)
peak_start = int(full_datetime.timestamp())
peak_end = peak_start + duration * 60 # duration in minutes to seconds
peak_timestamps = np.arange(peak_start, peak_end, dt, dtype=int)
common, indices_ts, _ = np.intersect1d(
timestamps, peak_timestamps, return_indices=True
)
peak_indices[indices_ts] = peak_occurence_no
peak_occurence_no += 1
pl.plot(peak_indices, label="Peak Indices")
pl.show()
return processed_times