Reputation: 6713
I got a string date
date = '2014-12-18T19:00:00-07:00'
But I have no idea how to save this to models.DateTimeField( null=True,blank=True)
Please help me how to convert this sting to datetime object Thank you very much
Upvotes: 2
Views: 7506
Reputation: 1173
Traditionally, see https://docs.python.org/3/library/time.html#time.strptime
# %z is supported in Python 3.2 onwards. Older versions of python don't support that.
from datetime import datetime
date = '2014-12-18T19:00:00-07:00'
format = "%Y-%m-%dT%H:%M:%S%z"
datetime_obj = datetime.strptime(date, format)
print datetime_obj.strftime(format)
Alternatively, because you have an iso8601 sting format already, someone already wrote a parser for that. See http://pypi.python.org/pypi/python-dateutil/1.5
import dateutil.parser
date = '2014-12-18T19:00:00-07:00'
datetime_obj = dateutil.parser.parse(date)
Upvotes: 8
Reputation: 23098
import datetime
format = "%Y-%m-%d %I:%M%p" # the format your input date is in
date_obj = datetime.datetime.strptime(date, format)
Upvotes: 0