Slice two datetime objects with Python

41 Views Asked by At

I have two date time objects in Python 2.7.

The first looks like this:

2018-09-22 00:00:00

and the second looks like this:

1899-12-30 17:20:59

I would like to end up with the dates from the first datetime object and the time from the second datetime object.

2018-09-22 17:20:59

Unfortunately I am coding for some old GIS software and compelled to use 2.7 Any help is appreciated.

2

There are 2 best solutions below

0
buran On BEST ANSWER

Have a look at datetime.datetime.replace() and datetime.datetime.combine() methods:

>>> from datetime import datetime
>>> dt1 = datetime.strptime('2018-09-22 00:00:00', '%Y-%m-%d %H:%M:%S')
>>> dt2 = datetime.strptime('1899-12-30 17:20:59', '%Y-%m-%d %H:%M:%S')
>>> dt3 = dt1.replace(hour=dt2.hour, minute=dt2.minute, second=dt2.second)
>>> dt3
datetime.datetime(2018, 9, 22, 17, 20, 59)

# or even better
>>> dt4=datetime.combine(dt1.date(), dt2.time())
>>> dt4
datetime.datetime(2018, 9, 22, 17, 20, 59)
0
JRiggles On

If both of these timestamps are datetime objects, you should be able to parse out portions of them like so

import datetime as dt


fmt = '%Y-%d-%m %H:%M:%S'

one = dt.datetime.strptime('2018-09-22 00:00:00', fmt)
two = dt.datetime.strptime('1899-12-30 17:20:59', fmt)

# get the 'date' from the first timestamp
# get the 'time' from the second timestamp
# create a new datetime object with this info
new_timestamp = dt.datetime.combine(one.date(), two.time())

print(new_timestamp)
# => 2018-09-22 17:20:59