问题描述
如何在 Python 中将 datetime-local(html 表单类型)转换为 datetime? 我的html代码是:
<input type="datetime-local" class="form-control" id="istart">
当我收到 POST 请求时,istart 值出现在一个字符串中。
从 Post Request 我收到: u'2015-01-02T00:00'
,我想将它解析为 Datetime 以插入数据库(通过 sqlalchemy)。
1楼
from datetime import datetime
datetime.strptime('2015-01-02T00:00', '%Y-%m-%dT%H:%M')
2楼
您可以通过将输入字符串分解为一系列值,将这些值转换为整数,然后将该序列输入datetime.datetime()
来解析输入字符串。
长格式:
date_in = u'2015-01-02T00:00' # replace this string with whatever method or function collects your data
date_processing = date_in.replace('T', '-').replace(':', '-').split('-')
date_processing = [int(v) for v in date_processing]
date_out = datetime.datetime(*date_processing)
>>> date_out
... datetime.datetime(2015, 1, 2, 0, 0)
>>> str(date_out)
... '2015-01-02 00:00:00'
......或者作为一个[明显不太可读的]单身人士:
date_in = u'2015-01-02T00:00'
date_out = datetime.datetime(*[int(v) for v in date_in.replace('T', '-').replace(':', '-').split('-')])
注意:可能有更有效的处理方法,使用regex
或其他方法。
datetime
也可能有一个我不知道的本地解释器。