Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert datetime-local to datetime in Python?

Tags:

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).

like image 720
urb Avatar asked Sep 16 '25 02:09

urb


2 Answers

from datetime import datetime
datetime.strptime('2015-01-02T00:00', '%Y-%m-%dT%H:%M')
like image 176
Alex G Avatar answered Sep 17 '25 18:09

Alex G


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.

like image 45
Augusta Avatar answered Sep 17 '25 18:09

Augusta