1. from datetime import datetime, timedelta
  2. def time_transformations(time_data, transformation_type, **kwargs):
  3. """
  4. Transforms a list of time values. For development/testing only.
  5. Args:
  6. time_data (list): A list of datetime objects or strings representing time.
  7. transformation_type (str): The type of transformation to apply.
  8. Valid options: "add_seconds", "subtract_minutes", "format_time"
  9. **kwargs: Keyword arguments specific to the transformation type.
  10. Returns:
  11. list: A list of transformed datetime objects or strings. Returns an empty list on error.
  12. """
  13. transformed_data = []
  14. if not time_data:
  15. return transformed_data # Return empty list if input is empty
  16. for time_value in time_data:
  17. try:
  18. if isinstance(time_value, str):
  19. dt = datetime.fromisoformat(time_value) #convert from string to datetime
  20. elif isinstance(time_value, datetime):
  21. dt = time_value
  22. else:
  23. print(f"Invalid time format: {time_value}. Skipping.")
  24. continue
  25. if transformation_type == "add_seconds":
  26. seconds = kwargs.get("seconds")
  27. if seconds is not None:
  28. dt += timedelta(seconds=seconds)
  29. else:
  30. print("Missing 'seconds' argument for add_seconds. Skipping.")
  31. continue
  32. elif transformation_type == "subtract_minutes":
  33. minutes = kwargs.get("minutes")
  34. if minutes is not None:
  35. dt -= timedelta(minutes=minutes)
  36. else:
  37. print("Missing 'minutes' argument for subtract_minutes. Skipping.")
  38. continue
  39. elif transformation_type == "format_time":
  40. format_string = kwargs.get("format")
  41. if format_string is not None:
  42. formatted_time = dt.strftime(format_string)
  43. transformed_data.append(formatted_time)
  44. else:
  45. print("Missing 'format' argument for format_time. Skipping.")
  46. continue
  47. else:
  48. print(f"Invalid transformation type: {transformation_type}. Skipping.")
  49. continue
  50. transformed_data.append(dt)
  51. except ValueError as e:
  52. print(f"Error processing time {time_value}: {e}. Skipping.")
  53. continue
  54. return transformed_data
  55. if __name__ == '__main__':
  56. # Example usage
  57. time_values = ["2023-10-26T10:00:00", datetime(2023, 10, 26, 12, 0, 0), "2023-10-27T14:30:00"]
  58. # Add 30 seconds to each time value
  59. transformed_time = time_transformations(time_values, "add_seconds", seconds=30)
  60. print(f"Added 30 seconds: {transformed_time}")
  61. # Subtract 15 minutes from each time value
  62. transformed_time = time_transformations(time_values, "subtract_minutes", minutes=15)
  63. print(f"Subtracted 15 minutes: {transformed_time}")
  64. # Format time as HH:MM:SS
  65. transformed_time = time_transformations(time_values, "format_time", format="%H:%M:%S")
  66. print(f"Formatted as HH:MM:SS: {transformed_time}")

Add your comment