Datetime utility functions

Tim Peters tim.one at comcast.net
Tue Sep 16 11:28:58 EDT 2003


[Paul Moore, finding the end of the month]
>> The best solution I could find was
>>
>> def month_end(dt):
>>    # Get the next month
>>    y, m = dt.year, dt.month
>>    if m == 12:
>>        y += 1
>>        m = 1
>>    else:
>>        m += 1
>>
>>    # Use replace to cater for both datetime and date types. This
>>    # leaves the time component of a datetime unchanged - it's
>>    # arguable whether this is the right thing.
>>
>>    return dt.replace(year=y, month=m, day=1) - datetime.timedelta(days=1)

[Christos TZOTZIOY Georgiou]
> I sent my own version without having seen your own --and mine might
> seem obfuscated, compared to yours.  Only a minor suggestion: don't
> use dt.replace, use dt.__class__ instead, since you wouldn't want your
> function to have side-effects (that is, don't destroy the actual
> object that dt is bound to.)

It's OK to use replace:  datetime and date (also time and timedelta) objects
are immutable -- their values can't be changed after initialization.  In
particular, x.replace() doesn't mutate x.

>>> import datetime
>>> t = datetime.datetime.today()
>>> t
datetime.datetime(2003, 9, 16, 11, 26, 16, 810000)
>>> t.replace(year=1, month=1, microsecond=42)
datetime.datetime(1, 1, 16, 11, 26, 16, 42)
>>> t	# unchanged
datetime.datetime(2003, 9, 16, 11, 26, 16, 810000)
>>>






More information about the Python-list mailing list