isodatetime.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. This module defines a method to parse an ISO 8601:2004 date time string.
  3. For this job it uses the parse_date and parse_time methods defined in date
  4. and time module.
  5. """
  6. from datetime import datetime
  7. from isodate.isodates import parse_date
  8. from isodate.isoerror import ISO8601Error
  9. from isodate.isostrf import DATE_EXT_COMPLETE, TIME_EXT_COMPLETE, TZ_EXT, strftime
  10. from isodate.isotime import parse_time
  11. def parse_datetime(datetimestring):
  12. """
  13. Parses ISO 8601 date-times into datetime.datetime objects.
  14. This function uses parse_date and parse_time to do the job, so it allows
  15. more combinations of date and time representations, than the actual
  16. ISO 8601:2004 standard allows.
  17. """
  18. try:
  19. datestring, timestring = datetimestring.split("T")
  20. except ValueError:
  21. raise ISO8601Error(
  22. "ISO 8601 time designator 'T' missing. Unable to"
  23. " parse datetime string %r" % datetimestring
  24. )
  25. tmpdate = parse_date(datestring)
  26. tmptime = parse_time(timestring)
  27. return datetime.combine(tmpdate, tmptime)
  28. def datetime_isoformat(
  29. tdt, format=DATE_EXT_COMPLETE + "T" + TIME_EXT_COMPLETE + TZ_EXT
  30. ):
  31. """
  32. Format datetime strings.
  33. This method is just a wrapper around isodate.isostrf.strftime and uses
  34. Extended-Complete as default format.
  35. """
  36. return strftime(tdt, format)