date_converters.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """This module is designed for community supported date conversion functions"""
  2. import numpy as np
  3. from pandas._libs.tslibs import parsing
  4. def parse_date_time(date_col, time_col):
  5. date_col = _maybe_cast(date_col)
  6. time_col = _maybe_cast(time_col)
  7. return parsing.try_parse_date_and_time(date_col, time_col)
  8. def parse_date_fields(year_col, month_col, day_col):
  9. year_col = _maybe_cast(year_col)
  10. month_col = _maybe_cast(month_col)
  11. day_col = _maybe_cast(day_col)
  12. return parsing.try_parse_year_month_day(year_col, month_col, day_col)
  13. def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col, second_col):
  14. year_col = _maybe_cast(year_col)
  15. month_col = _maybe_cast(month_col)
  16. day_col = _maybe_cast(day_col)
  17. hour_col = _maybe_cast(hour_col)
  18. minute_col = _maybe_cast(minute_col)
  19. second_col = _maybe_cast(second_col)
  20. return parsing.try_parse_datetime_components(
  21. year_col, month_col, day_col, hour_col, minute_col, second_col
  22. )
  23. def generic_parser(parse_func, *cols):
  24. N = _check_columns(cols)
  25. results = np.empty(N, dtype=object)
  26. for i in range(N):
  27. args = [c[i] for c in cols]
  28. results[i] = parse_func(*args)
  29. return results
  30. def _maybe_cast(arr):
  31. if not arr.dtype.type == np.object_:
  32. arr = np.array(arr, dtype=object)
  33. return arr
  34. def _check_columns(cols):
  35. if not len(cols):
  36. raise AssertionError("There must be at least 1 column")
  37. head, tail = cols[0], cols[1:]
  38. N = len(head)
  39. for i, n in enumerate(map(len, tail)):
  40. if n != N:
  41. raise AssertionError(
  42. f"All columns must have the same length: {N}; "
  43. f"column {i} has length {n}"
  44. )
  45. return N