使用strptime时,忽略来自日期时间戳的未转换数据

时间:2016-11-11 06:09:33

标签: python-3.5 strptime

第三方API会返回包含日期时间戳的CSV数据,如下所示:

InvalidArgumentError (see above for traceback): Cannot assign a device to node 'fifo_queue': Could not satisfy explicit device specification '/device:GPU:0' because no supported kernel for GPU devices is available.

我必须以格式dtval = '2016-10-14 05:09:30+00:00' 转换它。

在这里,我不确定指令的最后+ XX:XX:

mm/dd/yyyy

我尝试了以下但没有奏效:

datetime.datetime.strptime(dtval, "%Y-%m-%d %H:%M:%S+XX:XX").strftime('%m/%d/%Y') 

Python3.4 +的datetime模块中是否有任何选项可以忽略重新转换未转换的数据?

我经历了this,但没有找到任何此类选项

1 个答案:

答案 0 :(得分:0)

经过一番研究后,我在django的源代码中发现了这个问题:

class FixedOffset(tzinfo):
    """
    Fixed offset in minutes east from UTC. Taken from Python's docs.
    Kept as close as possible to the reference version. __init__ was changed
    to make its arguments optional, according to Python's requirement that
    tzinfo subclasses can be instantiated without arguments.
    """

    def __init__(self, offset=None, name=None):
        if offset is not None:
            self.__offset = timedelta(minutes=offset)
        if name is not None:
            self.__name = name

    def utcoffset(self, dt):
        return self.__offset

    def tzname(self, dt):
        return self.__name

    def dst(self, dt):
        return timedelta(0)
    def get_timezone(offset):
        """
        Returns a tzinfo instance with a fixed offset from UTC.
        """
        if isinstance(offset, timedelta):
            offset = offset.seconds // 60
        sign = '-' if offset < 0 else '+'
        hhmm = '%02d%02d' % divmod(abs(offset), 60)
        name = sign + hhmm
        return FixedOffset(offset, name)


def custom_strptime(self, value):
    """Parses a string and return a datetime.datetime.
    This function supports time zone offsets. When the input contains one,
    the output uses a timezone with a fixed offset from UTC.
    Raises ValueError if the input is well formatted but not a valid datetime.
    Returns None if the input isn't well formatted.
    """
    datetime_re = re.compile(
        r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
        r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
        r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
        r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
    )
    match = datetime_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_timezone(offset)
            kw = {k: int(v) for k, v in kw.items() if v is not None}

        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw)