Esempio n. 1
0
    def extract(cls, timestamp_str, timezone):
        """
        Tries to extract a `datetime` object from the given string. First the
        datetime format is tried, if it fails, the date format is used for
        extraction.

        Raises `PolyaxonDateTimeFormatterException` if the extraction fails.
        """
        if not timestamp_str:
            raise PolyaxonDateTimeFormatterException(
                "timestamp_str must a valid string, received {}".format(timestamp_str)
            )

        if not timezone:
            raise PolyaxonDateTimeFormatterException(
                "timezone is required, received {}".format(timezone)
            )

        if isinstance(timestamp_str, (date, datetime)):
            return timestamp_str

        try:
            return cls.extract_datetime(timestamp_str, timezone=timezone)
        except PolyaxonDateTimeFormatterException:
            pass

        try:
            return cls.extract_datetime_hour(timestamp_str, timezone=timezone)
        except PolyaxonDateTimeFormatterException:
            pass

        # We leave it to raise
        return cls.extract_date(timestamp_str, timezone=timezone)
Esempio n. 2
0
    def format_datetime(cls, timestamp):
        """
        Creates a string representing the date and time information provided by
        the given `timestamp` object.
        """
        if not timestamp:
            raise PolyaxonDateTimeFormatterException(
                "timestamp must a valid string {}".format(timestamp))

        return timestamp.strftime(cls.DATETIME_FORMAT)
Esempio n. 3
0
    def extract_datetime_hour(cls, datetime_str, timezone):
        """
        Tries to extract a `datetime` object from the given string, including only hours.

        Raises `PolyaxonDateTimeFormatterException` if the extraction fails.
        """
        if not datetime_str:
            raise PolyaxonDateTimeFormatterException(
                "datetime_str must a valid string")

        if not timezone:
            raise PolyaxonDateTimeFormatterException(
                "timezone is required, received {}".format(timezone))

        try:
            return cls._extract_timestamp(datetime_str,
                                          cls.DATETIME_HOUR_FORMAT,
                                          timezone=timezone)
        except (TypeError, ValueError):
            raise PolyaxonDateTimeFormatterException(
                "Invalid datetime string {}.".format(datetime_str))