Reputation: 12084
I have a field where users can choose vehicle warranty. They can choose 1 year, 2, years and end datum.
When I get it from the database it's unicoded.
When I do print(car['warranty'])
I get 2019-12-20T08:59:49.897Z"
When I do print(type(car["warranty"]))
I get <type 'unicode'>
.
How can I convert it and check if it's a date or if it's a or something else. Depending on that I want to show a label:
I use python 2.7.
UPDATE
I get the data from database as follows:
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'),
UPDATE
The lead_data['sale']
is as follows:
{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'}
Upvotes: 1
Views: 181
Reputation: 10392
There's an older library that does exactly what you want called iso8601. It parses ISO8601 formatted datetime strings (which is what you have). It's been well tested over 10 years. However, as the README on that library says, python-dateutil
will also parse ISO8601 strings and a whole lot more.
Upvotes: 0
Reputation: 8740
You can also try below code.
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
Steps to understand above on Python's Interactive console:
>>> 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
>>>
Upvotes: 0
Reputation: 370
Your date is in an ISO-style format commonly found in Javascript/JSON. The final Z means that it is a UTC datetime; you will most likely want this to be converted to your local time at some point. To convert it to a datetime object in Python, you should use the datetime module. The datetime module has three main classes of interest here: datetime.datetime, datetime.date and datetime.time which represent a date and time, just a date and just a time respectively.
There is a method fromisoformat() on each of these which accepts an ISO-style string but unfortunately it is only available from Python 3.7 onwards...
Instead we must use the method strptime, which accepts a string and a formatting string, after slightly modifying the string. I will assume that we want our datetime object to keep the knowledge of the timezone so we can output the datetime in our chosen time zone later, but unfortunately strptime will not accept the Z specifier (hence our need to modify the string.
Moreover, in versions of python below 3.2, strptime will not produce an 'aware' object (aware of the timezone) even when passing a timezone specified it does recognise. So to do this properly, we have to go through this rather involved faff:
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!'
Upvotes: 0
Reputation: 17
Take a look at dateutil.parse. datetime could be useful too.
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'
Upvotes: 1
Reputation: 1193
To convert the first result into DateTime object use ->
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'
Upvotes: 0