Reputation: 936
I am trying to convert a time string into a datetime
object where the date is today's date. However, I only have a time string and its replace()
method does not seem to work.
from datetime import datetime, time,date
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
print startTime
>>> 1900-01-01 09:30:00
I want:
2017-01-20 09:30:00
Upvotes: 2
Views: 3372
Reputation: 14216
Here is another solution using another library.
import pendulum
timestr = "9:30"
dt = pendulum.parse(timestr)
<Pendulum [2017-01-20T09:30:00+00:00]>
Or
dt = pendulum.parse(timestr).to_datetime_string()
'2017-01-20 09:30:00'
Upvotes: -1
Reputation: 11573
nicer than replace
is combine
:
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
d = datetime.combine(datetime.today(), startTime.time())
Upvotes: 3
Reputation: 140148
replace
doesn't work in-place. Don't ignore the return value, assign it back like this:
startTime = startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
and you get:
2017-01-20 09:30:00
Upvotes: 0