3

My question is very similar to this question but with an important difference.

I have two datetime objects like

In [87]: d
Out[87]: datetime.datetime(1900, 1, 1, 2, 0)
In [88]: m
Out[88]: datetime.datetime(1900, 1, 1, 6, 0)

I want to add the time part of d to m to get

datetime.datetime(1900, 1, 1, 8, 0)

The other question gives me datetime.datetime(1900, 1, 1, 2, 0) when i combine m and d.time() as

In [90]: print datetime.datetime.combine(m, d.time())
1900-01-01 02:00:00

I know that the other way of doing this would be to use timedelta as

In [91]: print m + datetime.timedelta(hours=d.hour, minutes=d.minute)
1900-01-01 08:00:00

But, is there a more pythonic way?

2
  • so you want to sum just the time portions of the dates, regardless of the date portion? Then your only option is the one you already found. Commented Sep 2, 2013 at 12:26
  • seems pretty pythonic to me Commented Sep 2, 2013 at 12:28

1 Answer 1

1

You could do this:

In [1]: import datetime as DT

In [2]: d = DT.datetime(1900,1,1,2,0)

In [3]: m = DT.datetime(1900,1,1,6,0)

In [4]: delta = d - DT.datetime(1900,1,1,0,0)

In [5]: m + delta
Out[5]: datetime.datetime(1900, 1, 1, 8, 0)

But note that this will give you a different answer if the year/month/date of d are different than 1900/1/1.

Sign up to request clarification or add additional context in comments.

2 Comments

You could use d - DT.datetime.combine(d.date(), DT.time.min) to create a delta. Or just DT.timedelta(hours=d.hour, minutes=d.minute, seconds=d.second), but the OP already figured that much out.
Yup, To clarify, I actually just need to add two times but I guess thats not there so I'm loading them into datetime objects using strptime. So, the date being different wont be a problem here I think. Thanks!

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.