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!
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.
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).
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With