1. import datetime
  2. def deserialize_timestamps(timestamps, version=None):
  3. """
  4. Deserializes timestamps from a string or list, supporting older versions.
  5. Args:
  6. timestamps (str or list): String of comma-separated timestamps or a list of datetime objects.
  7. version (int, optional): Version of the timestamp format. Defaults to None.
  8. Returns:
  9. list: A list of datetime objects. Returns an empty list if input is invalid.
  10. """
  11. if isinstance(timestamps, str):
  12. try:
  13. timestamp_strings = timestamps.split(',')
  14. timestamps_list = []
  15. for ts_str in timestamp_strings:
  16. ts_str = ts_str.strip()
  17. if ts_str: # Avoid empty strings
  18. try:
  19. # Attempt to parse as ISO format (version 1)
  20. dt = datetime.datetime.fromisoformat(ts_str.replace('Z', '+00:00'))
  21. timestamps_list.append(dt)
  22. except ValueError: #Handle older formats
  23. try:
  24. #Attempt to parse as a simple string format (version 0)
  25. dt = datetime.datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S")
  26. timestamps_list.append(dt)
  27. except ValueError:
  28. print(f"Invalid timestamp format: {ts_str}")
  29. return [] # Return empty list on error
  30. return timestamps_list
  31. except Exception:
  32. return []
  33. elif isinstance(timestamps, list):
  34. timestamps_list = []
  35. for ts in timestamps:
  36. if isinstance(ts, str):
  37. try:
  38. dt = datetime.datetime.fromisoformat(ts.replace('Z', '+00:00'))
  39. timestamps_list.append(dt)
  40. except ValueError:
  41. try:
  42. dt = datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S")
  43. timestamps_list.append(dt)
  44. except ValueError:
  45. print(f"Invalid timestamp format: {ts}")
  46. return []
  47. elif isinstance(ts, datetime.datetime):
  48. timestamps_list.append(ts)
  49. else:
  50. print(f"Invalid timestamp type: {type(ts)}")
  51. return []
  52. return timestamps_list
  53. else:
  54. print("Invalid input type. Must be string or list.")
  55. return [] # Return empty list on error
  56. if __name__ == '__main__':
  57. # Example Usage
  58. timestamps_str = "2023-10-26 10:00:00,2023-10-27 12:30:00"
  59. timestamps_list = [datetime.datetime(2023, 10, 26, 10, 0, 0), datetime.datetime(2023, 10, 27, 12, 30, 0)]
  60. timestamps_mixed = ["2023-10-26 10:00:00", datetime.datetime(2023, 10, 27, 12, 30, 0)]
  61. deserialized_str = deserialize_timestamps(timestamps_str)
  62. deserialized_list = deserialize_timestamps(timestamps_list)
  63. deserialized_mixed = deserialize_timestamps(timestamps_mixed)
  64. print(f"Deserialized string: {deserialized_str}")
  65. print(f"Deserialized list: {deserialized_list}")
  66. print(f"Deserialized mixed: {deserialized_mixed}")
  67. #Example with invalid input
  68. invalid_timestamps = "2023-10-26 10:00:00,invalid-date"
  69. invalid_result = deserialize_timestamps(invalid_timestamps)
  70. print(f"Invalid timestamps result: {invalid_result}")

Add your comment