Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to combine date and time strings to single datetime object using Python

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? Any clues would be great!

like image 632
MFB Avatar asked Mar 06 '12 06:03

MFB


People also ask

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do you convert a date object to a datetime object in Python?

You can use the datetime module's combine method to combine a date and a time to create a datetime object. If you have a date object and not a time object, you can initialize the time object to minimum using the datetime object(minimum time means midnight).

Which of the following will create a date and time using date and time in Python?

now() , and datetime. combine() to create instances of date , datetime , and time objects. Each instance is stored in a different variable: today is a date instance that has only the year, month, and day.


1 Answers

Use datetime.combine:

import datetime as dt mytime = dt.datetime.strptime('0130','%H%M').time() mydatetime = dt.datetime.combine(dt.date.today(), mytime) 
like image 127
mechanical_meat Avatar answered Sep 20 '22 13:09

mechanical_meat