Yax Yax - 1 month ago 5
Python Question

How To Covert 7:00pm to Python Datetime object

I have a Schedule table with start_time column which stores time in this format,

4:00pm

7:04pm

5:00am

I want to be able to start an event for users base on the start_time they selected every day.

How do I convert 7:00pm to

datetime
object or what is the best way to achieve this?

Answer
# time objects have no strptime method, so use datetime's, but it sets the
# date to 1900-01-01 by default
wrong_date = datetime.datetime.strptime('7:00pm', '%I:%M%p')
# replace 1900-01-01 with the actual date
correct_date = datetime.datetime.combine(datetime.date.today(), wrong_date.time())
# correct_date is now datetime.datetime(2016, 10, 22, 19, 0)