ninesalt
ninesalt

Reputation: 4354

Use current month/day in datetime parse

I'm trying to parse a string that is just '07:43 PM'. I figured out the strptime() function but when I print the result the day, month and year are all wrong. It's not using the current time, it uses 1, 1 and 1900 respectively. A naive solution to this I found would be to just use .replace() and replace the day, month and year with the current values. Is there something else I can do?

y = '07:43 PM'
print(datetime.strptime(y, '%I:%M %p'))  #1900-01-01 19:43:00

Upvotes: 1

Views: 39

Answers (1)

As the comment said you can get the now time then update those fields with what you want such as:

from datetime import datetime
y = '07:43 PM'
now, stripped = datetime.now(), datetime.strptime(y, '%I:%M %p')
now = now.replace(hour=stripped.hour, minute=stripped.minute)
print(now)

Upvotes: 2

Related Questions