Reputation:
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'
Upvotes: 1
Views: 2637
Reputation: 365607
If you just read the docs for datetime
, or look at the help(datetime)
in the interactive interpreter, you'll see the combine
method:
classmethod
datetime.combine(date, time)
Return a new
datetime
object whose date components are equal to the givendate
object’s, and whose time components andtzinfo
attributes are equal to the giventime
object’s. For anydatetime
object d,d == datetime.combine(d.date(), d.timetz())
. If date is adatetime
object, its time components andtzinfo
attributes are ignored.
So, you don't have to write the method yourself; it's already there in the module.
Of course you need to parse that time_str
into a time
object, but you clearly already know how to do that.
But if you did want to write it yourself, formatting the date and time as strings just to parse them back out would be silly. Why not just access the attributes directly?
return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)
Upvotes: 5