2

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

2
  • do you care about the timezone? Commented Dec 16, 2014 at 1:27
  • yes,I want to change to UTC Commented Dec 16, 2014 at 1:28

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! It's very clearly.I have a question,is datetime_obj a UTC time???
It is, but you can convert it to a timestamp in your TZ via 'datetime.astimezone(tz)' You can set it via the constructor too, but in this particular case, you're not instantiating a DT Object from the constructor call. You're parsing an iso8601 string to DT object.
0
import datetime
format = "%Y-%m-%d %I:%M%p" # the format your input date is in
date_obj = datetime.datetime.strptime(date, format)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.