urb
urb

Reputation: 964

How convert datetime-local to datetime in Python?

How convert datetime-local (html form type) to datetime in Python? My html code is:

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

When I receive the POST request the istart value comes in a string.

From Post Request I receive that: u'2015-01-02T00:00' and I want to parse it to Datetime for insert in database (via sqlalchemy).

Upvotes: 4

Views: 5071

Answers (2)

Alex G
Alex G

Reputation: 111

from datetime import datetime
datetime.strptime('2015-01-02T00:00', '%Y-%m-%dT%H:%M')

Upvotes: 11

Augusta
Augusta

Reputation: 7221

You can parse your input string by breaking it into a sequence of values, converting the values to integers, and then feeding that sequence into datetime.datetime().

In long form:

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'

...or as a [substantially less readable] singleton:

date_in = u'2015-01-02T00:00' 
date_out = datetime.datetime(*[int(v) for v in date_in.replace('T', '-').replace(':', '-').split('-')])

Note: There may be more efficient ways of processing this, using regex or somesuch. datetime may have a native interpreter that I don't know about, as well.

Upvotes: 2

Related Questions