Say you have a datetime.date
object such as that returned by datetime.date.today()
.
Then later on you also get a string representing the time that complements the date object.
What is a pythonic way of combining these two in a datetime.datetime object? More specifically, can I avoid converting the date object to a string?
This is how I get it done for now:
def combine_date_obj_and_time_str(date_obj, time_str):
# time_str has this form: 03:40:01 PM
return datetime.datetime.strptime(date_obj.strftime("%Y-%m-%d") + ' ' + time_str, "%Y-%m-%d %I:%M:%S %p")
EDIT:
I looked into datetime.datetime.combine
as the first answer describes, but I am a bit at loss with getting the time string into a time object:
>>> datetime.datetime.combine(datetime.date.today(), time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'strptime'
time_str
?time.strptime(*args)
returnstime.struct_time()
, notdatetime.time()
. To get the latter, calldatetime.strptime(*args).time()
.