Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create datetime from "%H:%M:%S"

Say I got some string with format %H:%M:%S, e.g. 04:35:45. I want to convert them to datetime.datetime object, year/month/day are the same as datetime.datetime.now().

I tried

now = datetime.now()
datetime_obj = datetime.strptime(time_string, "%H:%M:%S")
datetime_obj.year = now.year
datetime_obj.month = now.month
datetime_obj.day = now.day

This won't work since year/month/day are read-only properties. So what's the best solution for this?

like image 482
laike9m Avatar asked Jan 06 '16 15:01

laike9m


1 Answers

You want datetime.combine(date, time):

>>> time = datetime.datetime.strptime("04:35:45", "%H:%M:%S").time()
>>> time
datetime.time(4, 35, 45)
>>> day = datetime.datetime.now().date()
>>> day
datetime.date(2016, 1, 6)
>>> datetime.datetime.combine(day, time)
datetime.datetime(2016, 1, 6, 4, 35, 45)
>>> 
like image 191
bruno desthuilliers Avatar answered Oct 06 '22 04:10

bruno desthuilliers