Easiest way to combine date and time strings to single datetime object using Python
Question:
I have a web form which has 2 input fields, "StartDate" and "StartTime". I convert the StartDate
field’s string into a Python datetime
object, no problem. The StartTime
field is passed in as a string in the form "0130" for 1:30am. What is the best way to convert the StartTime
string and combine it with the StartDate
datetime
object so that both are stored as a single datetime
?
Answers:
Use datetime.combine:
import datetime as dt
mytime = dt.datetime.strptime('0130','%H%M').time()
mydatetime = dt.datetime.combine(dt.date.today(), mytime)
If you can load the time into a datetime.time
, you can use the following code
import datetime
dt = datetime.datetime(2012, 2, 12)
tm = datetime.time(1, 30)
combined = dt.combine(dt, tm)
print(combined)
Output
2012-02-12 01:30:00
Just a short version:
from datetime import datetime
print datetime.combine(datetime.strptime("5 Mar 12", "%d %b %y"), datetime.strptime("0130","%H%M").time())
Output
2012-03-05 01:30:00
import datetime
def time_tango(date, time):
return datetime.datetime.combine(date, time)
I have a web form which has 2 input fields, "StartDate" and "StartTime". I convert the StartDate
field’s string into a Python datetime
object, no problem. The StartTime
field is passed in as a string in the form "0130" for 1:30am. What is the best way to convert the StartTime
string and combine it with the StartDate
datetime
object so that both are stored as a single datetime
?
Use datetime.combine:
import datetime as dt
mytime = dt.datetime.strptime('0130','%H%M').time()
mydatetime = dt.datetime.combine(dt.date.today(), mytime)
If you can load the time into a datetime.time
, you can use the following code
import datetime
dt = datetime.datetime(2012, 2, 12)
tm = datetime.time(1, 30)
combined = dt.combine(dt, tm)
print(combined)
Output
2012-02-12 01:30:00
Just a short version:
from datetime import datetime
print datetime.combine(datetime.strptime("5 Mar 12", "%d %b %y"), datetime.strptime("0130","%H%M").time())
Output
2012-03-05 01:30:00
import datetime
def time_tango(date, time):
return datetime.datetime.combine(date, time)