0

Well, I have datetime objects with information like 2013-10-01 14:15:00 and time objects like

  1. 1900-01-01 00:00:49.235000
  2. 1900-01-01 00:00:49.465000
  3. 1900-01-01 00:00:49.695000

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:

  1. 2013-10-01 00:00:49.235000
  2. 2013-10-01 00:00:49.465000
  3. 2013-10-01 00:00:49.695000

Expected output:

  1. 2013-10-01 14:15:49.235000
  2. 2013-10-01 14:15:49.465000
  3. 2013-10-01 14:15:49.695000

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.