代码之家  ›  专栏  ›  技术社区  ›  Boky

转换为日期的正确方法

  •  1
  • Boky  · 技术社区  · 7 年前

    我有一个用户可以选择车辆保修的字段。他们可以选择1年、2年和结束日期。

    当我从数据库中得到它时,它是单独编码的。

    当我这样做的时候 print(car['warranty']) 2019-12-20T08:59:49.897Z"

    当我这样做的时候 print(type(car["warranty"])) 我明白了 <type 'unicode'> .

    • 有效期至格式化日期
    • 如果是我想显示的数字: 2年保修

    使现代化

    我从数据库中获得的数据如下:

    item = Item.objects.get(pk=lead.item_id)
    lead_data = json.loads(item.data, object_hook=json_util.object_hook)
    
    warranty = (lead_data['sale']['warranty_end'] if lead_data['sale']['warranty'] == '0' else get_warranty_label(str(lead_data['sale']['warranty']))) if 'sale' in lead_data else get_warranty_label('1'),
    

    这个 lead_data['sale']

    {u'warranty': u'0', u'comment': u'', u'financing': u'NO', u'waranty_end': u'2019-12-30', u'usageDescription': u'', u'price': u'15000', u'financing_amount': u'0', u'label': u'', u'delivery': u'2018-12-21', u'warranty_end': u'2019-12-20T08:59:49.897Z"', u'deposit': u'0', u'kilometers': u'13000', u'usage': u'NO', u'deliveryText': u'2018-12-21', u'take_over': u'0', u'warranty_endText': u'20/12/2019', u'id': u'2af7bfe2-252f-4482-857f-8b03e28c748b', u'vat': u'21'}
    
    5 回复  |  直到 7 年前
        1
  •  1
  •   Lorran Rosa    7 年前

    看看 dateutil.parse datetime

    from dateutil.parser import parse
    
    def is_date(object):
        try:
            #Check if it's a date of any format.
            parse(object)
            return 'Valid until formated_date'
        except ValueError:
            #When cannot be a date
            return '2 year warranty'
    
        2
  •  0
  •   saviour123    7 年前

    要将第一个结果转换为DateTime对象,请使用->

    import datetime
    
    date_object = datetime.datetime.strptime("2019-12-20T08:59:49.897Z", '%Y-%m-%dT%H:%M:%S.%fZ')
    temp_date = date_object.date() # returns date
    # then convert to date.
    str(temp_date) # result '2019-12-20'
    
        3
  •  0
  •   Andrew McLeod    7 年前

    相反,我们必须使用strptime方法,它在稍微修改字符串后接受一个字符串和一个格式化字符串。我假设我们希望datetime对象保留时区信息,以便稍后可以在所选时区中输出datetime,但不幸的是,strTime将不接受Z说明符(因此需要修改字符串)。

    def process_datestring(my_date_string):
    
        # In Python 3, a UTC class exists
        import datetime
        try:
            from datetime import timezone
            utc = timezone.utc
        except ImportError:
            # Python 2
            class UTC(datetime.tzinfo):
                def utcoffset(self, dt):
                    return datetime.timedelta(0)
    
                def tzname(self, dt):
                    return "UTC"
    
                def dst(self, dt):
                    return datetime.timedelta(0)
        utc = UTC()
    
        # If we have a Z-terminated datetime string,
        # trim off the Z and build a UTC datetime object
        if my_date_string and my_date_string[-1] == 'Z':
            my_datetime = datetime.datetime.strptime(
                my_date_string[:-1], '%Y-%m-%dT%H:%M:%S.%f')
            my_datetime.replace(tzinfo=UTC())
            # Use this newly-created datetime object as you see fit
            return 'Valid until formated_date'
    
        # Otherwise, test for a simple date
    
        try:
            # Convert a string of form YYYY-MM-DD to a datetime object
            my_datetime = datetime.datetime.strptime(
                 my_date_string, '%Y-%m-%d')
            # This datetime object is naive - it is NOT timezone aware
            return 'Valid until formated_date'
        except ValueError:
            # Unable to convert this string - perhaps it is a number?
            try:
                # This will raise an exception if my_date_string is not
                # a simple number
                float(my_date_string)
                return '2 years warranty'
            except ValueError:
                # Not a number either; most likely an unhandled date format.
                raise ValueError('Unhandled string!')
    
    my_date_string = "2019-12-20T08:59:49.897Z"
    print(process_datestring(my_date_string))
    # returns 'Valid until formated_date'
    my_date_string = "2019-12-20"
    print(process_datestring(my_date_string))
    # returns 'Valid until formated_date'
    my_date_string = "3"
    print(process_datestring(my_date_string))
    # returns '2 years warranty'
    my_date_string = "test"
    print(process_datestring(my_date_string))
    # raises ValueError 'Unhandled string!'
    
        4
  •  0
  •   hygull    7 年前

    您也可以尝试下面的代码。

    from datetime import datetime
    
    def is_date(s):
        try:
            d = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ")   
    
            if type(d) is datetime:
                return True
            else:
                return False
        except:
            return False
    
    s = "2019-12-20T08:59:49.897Z"
    print(is_date(s)) # True
    
    s2 = "2019-12-20T08:59"
    print(is_date(s2)) # False
    

    在Python的交互式控制台上理解上述内容的步骤:

    >>> from datetime import datetime
    >>>
    >>> s = "2019-12-20T08:59:49.897Z"
    >>> type(s)
    <class 'str'>
    >>>
    >>> d = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ")
    >>> d
    datetime.datetime(2019, 12, 20, 8, 59, 49, 897000)
    >>>
    >>> type(d)
    <class 'datetime.datetime'>
    >>>
    >>> type(d) is datetime
    True
    >>>
    >>> type(d) is str
    False
    >>>
    >>> type(d) is int
    False
    >>>
    >>> type(d) is list
    False
    >>>
    >>> type(d) is tuple
    False
    >>>
    >>> type(d) is dict
    False
    >>>
    >>> type(d) is float
    False
    >>>
    >>> type(d) is complex
    False
    >>>
    
        5
  •  0
  •   Tim Tisdall    7 年前

    有一个旧的图书馆,它的功能正是你想要的 iso8601 python-dateutil 还将解析ISO8601字符串和更多字符串。