user1165419 user1165419 -5 years ago 275
Python Question

changing datetime format with strptime

I'm trying to add or minus time from a datetime object and then convert it to strptime but I'm getting an error message.

Here's an example of getting the 'hour' of a datetime object, adding + 1 to it and then trying to use strptime on it;

time1 = datetime.datetime.strptime("09/Sep/2015:08:00:00", "%d/%b/%Y:%H:%M:%S")

print time1.hour
print time1.hour + 1

> 8

time3 = time1.hour + 1
print time3.strptime('%H')

> print time3.strptime('%H')
AttributeError: 'int' object has no attribute 'strptime'

Is there any way to manipulate datetime objects and change its format (with strptime or similar)?

Answer Source

time1.hour is an int, 1 is an int, therfore time3 is an int, which is why you are getting this error.

You should also use strftime in your last line, not strptime.

You can use relativedelta or timedelta (see the comments), but I suppose that datetime.replace will be easier:

time1 = datetime.datetime.strptime("09/Sep/2015:08:00:00", "%d/%b/%Y:%H:%M:%S")

time3 = time1.replace(hour=time1.hour + 1)
print time3.strftime('%H')
>> 09

EDIT This will indeed fail for times after 23:00. Use the recommended approaches in the comments for a more robust solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download