How do I parse an ISO 8601-formatted date?

后端 未结 27 2323
小鲜肉
小鲜肉 2020-11-21 06:08

I need to parse RFC 3339 strings like \"2008-09-03T20:56:35.450686Z\" into Python\'s datetime type.

I have found strptime in the Python sta

27条回答
  •  盖世英雄少女心
    2020-11-21 06:31

    Django's parse_datetime() function supports dates with UTC offsets:

    parse_datetime('2016-08-09T15:12:03.65478Z') =
    datetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=)
    

    So it could be used for parsing ISO 8601 dates in fields within entire project:

    from django.utils import formats
    from django.forms.fields import DateTimeField
    from django.utils.dateparse import parse_datetime
    
    class DateTimeFieldFixed(DateTimeField):
        def strptime(self, value, format):
            if format == 'iso-8601':
                return parse_datetime(value)
            return super().strptime(value, format)
    
    DateTimeField.strptime = DateTimeFieldFixed.strptime
    formats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')
    

提交回复
热议问题