如何在Python中将datetimelocal转换为datetime?

2024-04-26 00:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中将本地日期时间(html表单类型)转换为datetime? 我的html代码是:

<input type="datetime-local" class="form-control" id="istart">

当我收到POST请求时,istart值以字符串形式出现。在

从Post请求中我收到了:u'2015-01-02T00:00',我想将它解析到Datetime以便插入数据库(通过sqlalchemy)。在


Tags: 代码formid表单类型inputdatetimelocal
1条回答
网友
1楼 · 发布于 2024-04-26 00:33:05

您可以通过将输入字符串分解为一系列值,将这些值转换为整数,然后将该序列输入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'

…或作为[基本上不太可读]的单例:

^{pr2}$

注意:可能有更有效的处理方法,使用regex或类似的方法。datetime可能还有一个我不知道的本地解释器。在

相关问题 更多 >