Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top