python:将字符串转换为时间对象

时间:2014-12-16 01:20:41

标签: python django

我收到了一个字符串date

date = '2014-12-18T19:00:00-07:00'

但我不知道如何将其保存到models.DateTimeField( null=True,blank=True)

请帮我解决如何将此sting转换为datetime对象的方法 非常感谢你

2 个答案:

答案 0 :(得分:6)

传统上,请参阅http://docs.python.org/2/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)

或者,因为你已经有了一个iso 8601字符串格式,所以有人已经为此编写了一个解析器。见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)

答案 1 :(得分:0)

import datetime
format = "%Y-%m-%d %I:%M%p" # the format your input date is in
date_obj = datetime.datetime.strptime(date, format)