Do datetime objects need to be deep-copied? Do datetime objects need to be deep-copied? python-3.x python-3.x

Do datetime objects need to be deep-copied?


Since all available types in the datetime module are documented as being immutable (right after the documentation of the classes it is stated):

Objects of these types are immutable.

you shouldn't worry about this.

Operations on a datetime instance will return a new instance thereby not affecting any other names that refer to the previous one.

You might want to take a look at the link provided by PM 2Ring that explains facts and myths about how names and values work. That should shed some light on any confusions you have about names.


There is nothing arbitrary about this.

All assignments in Python are references. No copying is ever done on assignment.

If you have the ability to mutate the object then any mutation will naturally affect all the references to that object.

The only reason you don't see this with integers or strings in your original code is that you're not mutating the objects, you're simply reassigning. Integers and strings, as well as datetimes, don't have any way of being mutated, so the only thing you can do is reassign them. If you reassigned a list, dict, or datetime, then you would not see the change propagated to other references, either.