1. from datetime import datetime, timedelta
  2. def validate_timestamps(data, expected_format="%Y-%m-%d %H:%M:%S"):
  3. """
  4. Validates a nested structure of timestamps.
  5. """
  6. def is_valid_timestamp(timestamp_value):
  7. """Checks if a single timestamp value is valid."""
  8. if not isinstance(timestamp_value, str):
  9. return False # Must be a string
  10. try:
  11. datetime.strptime(timestamp_value, expected_format)
  12. return True
  13. except ValueError:
  14. return False
  15. def validate_level(data_level):
  16. """Validates a single level of the nested structure."""
  17. if isinstance(data_level, list):
  18. for item in data_level:
  19. if not validate_level(item):
  20. return False
  21. return True
  22. elif isinstance(data_level, dict):
  23. for key, value in data_level.items():
  24. if not validate_level(value):
  25. return False
  26. return True
  27. elif isinstance(data_level, str):
  28. return is_valid_timestamp(data_level)
  29. elif isinstance(data_level, datetime):
  30. return True # Already a datetime object
  31. else:
  32. return True # Consider non-string/list/dict as valid
  33. return validate_level(data)
  34. if __name__ == '__main__':
  35. # Example Usage
  36. data1 = [
  37. "2023-10-26 10:00:00",
  38. {"event": "start", "time": "2023-10-26 10:05:00"},
  39. [1,2, "2023-10-26 10:10:00"]
  40. ]
  41. print(f"Data 1 is valid: {validate_timestamps(data1)}")
  42. data2 = {
  43. "start_time": "2023-10-26 10:00:00",
  44. "end_time": "2023-10-26 10:10:00",
  45. "intermediate": [
  46. "invalid_format",
  47. {"another_time": "2023-10-26 10:05:00"}
  48. ]
  49. }
  50. print(f"Data 2 is valid: {validate_timestamps(data2)}")
  51. data3 = [datetime(2023, 10, 26, 10, 0, 0), "2023-10-26 10:15:00"]
  52. print(f"Data 3 is valid: {validate_timestamps(data3)}")

Add your comment