Reputation: 163
Well, I have datetime objects with information like 2013-10-01 14:15:00 and time objects like
The time objects are actually progressive increments which I'd like to add to the datetime object. As described here,
If date is a datetime object, its time components and tzinfo attributes are ignored.
I wrote the code below. How should it be updated to be able to add these time objects to the datetime object as increments?
def CombineDateTime(date_str, time_str, date_fmt, time_fmt, equipment, sample_name):
import datetime
try:
date_obj = datetime.datetime.strptime(date_str, date_fmt)
time_obj = datetime.datetime.strptime(time_str, time_fmt)
return datetime.datetime.combine(date_obj.date(), time_obj.time())
except:
return 'Error'
Output:
Expected output:
Upvotes: 0
Views: 89
Reputation: 3787
The output that you get is because 2013-10-01
and 00:00:49.235000
to your datetime.datetime.combine() and the time present in date_obj 14:15:00
is not taken into consideration at that point!
Therefore, you have the add the date_obj timedelta to your time_obj before you combine!
date_time=date_obj.time()
time_obj += datetime.timedelta(hours=date_time.hour,minutes=date_time.minute,seconds=date_time.second,microseconds=date_time.microsecond)
That is,
def CombineDateTime(date_str, time_str, date_fmt, time_fmt, equipment, sample_name):
import datetime
try:
date_obj = datetime.datetime.strptime(date_str, date_fmt)
date_time=date_obj.time()
time_obj = datetime.datetime.strptime(time_str, time_fmt)
time_obj += datetime.timedelta(hours=date_time.hour,minutes=date_time.minute,seconds=date_time.second,microseconds=date_time.microsecond)
return datetime.datetime.combine(date_obj.date(),time_obj.time())
except Exception as e:
#print e
return 'Error'
Upvotes: 1