简体   繁体   中英

Adding a 'Datetime' object to a time delta

I'm new to python, and I'm trying to do some math on dates. The starting date is pulled from a swagger interface that can be found here: https://esi.tech.ccp.is/latest/#!/Market/get_markets_region_id_orders

The relevant field is the "issued" field. Currently I'm trying to add to that using a timedelta like this:

date = market_ops.data[i].issued completion_date = date + datetime.timedelta(days=int(market_ops.data[i].duration))

This returns the error: unsupported operand type(s) for +: 'Datetime' and 'datetime.timedelta'

Does this mean the "issued" object is not a datetime.datetime object, but some other type of object, or am I doing something else wrong?

I think you need to convert the string data into a datetime.datetime instance before adding the datetime.timedelta to it.

Something along these lines:

date_string = market_ops.data[i].issued
date = datetime.datetime.strptime(date_string[:10], '%Y-%m-%M')
completion_date = date + datetime.timedelta(days=int(market_ops.data[i].duration))

Note that the result in the calculated completion_date will also be of type datetime.datetime .

As @martineau suggested below, I just needed to stringify the 'Datetime' object, which is a swagger primitive, and then strptime() the resulting string as such:

start_date = datetime.datetime.strptime(str(market_ops.data[i].issued)[0:19],
                                              '%Y-%m-%dT%H:%M:%S') 
completion_date = start_date + datetime.timedelta(days=int(market_ops.data[i].duration))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM