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?
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)
>>>
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