daltonf
daltonf

Reputation: 460

Convert a time-only string such as "6:02PM" to a datetime object?

I have an input that is given in %I:%M%p (ex. "6:02PM"). I'm trying to input into this code to find the difference between now and then:

import datetime

now = datetime.now()
then = "6:02PM"
tdelta = now - then

Upvotes: 3

Views: 329

Answers (1)

unutbu
unutbu

Reputation: 880607

import datetime as dt

now = dt.datetime.now()
then = dt.datetime.combine(now, dt.datetime.strptime("6:02PM", "%I:%M%p").time())
print(then)
# 2012-08-26 18:02:00

tdelta = now - then
print(tdelta)
# -1 day, 20:53:25.190721

Upvotes: 3

Related Questions