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