Another surprise from the datetime module

R

Roy Smith

I was astounded just now to discover that datetime.timedelta doesn't
have a replace() method (at least not in Python 2.7). Is there some
fundamental reason why it shouldn't, or is this just an oversight?

My immediate use case was wanting to print a timedelta without the
fractions of seconds. The most straight-forward is:

print td.replace(microseconds=0)

but that doesn't work. Yes, I know I can use strftime, but (as I've
mentioned before :)), that requires dragging up the reference page to
figure out what grotty little format string I need. The brute-force

print timedelta(seconds=int(td.total_seconds()))

is easier than that, but plain old replace() would be even easier.
 
M

Mark Lawrence

I was astounded just now to discover that datetime.timedelta doesn't
have a replace() method (at least not in Python 2.7). Is there some
fundamental reason why it shouldn't, or is this just an oversight?

My immediate use case was wanting to print a timedelta without the
fractions of seconds. The most straight-forward is:

print td.replace(microseconds=0)

but that doesn't work. Yes, I know I can use strftime, but (as I've
mentioned before :)), that requires dragging up the reference page to
figure out what grotty little format string I need. The brute-force

print timedelta(seconds=int(td.total_seconds()))

is easier than that, but plain old replace() would be even easier.

datetime.timedelta doesn't have a strftime method either.

AttributeError: 'datetime.timedelta' object has no attribute 'strftime'
 
N

Neil Cerutti

I was astounded just now to discover that datetime.timedelta
doesn't have a replace() method (at least not in Python 2.7).
Is there some fundamental reason why it shouldn't, or is this
just an oversight?

My immediate use case was wanting to print a timedelta without
the fractions of seconds. The most straight-forward is:

print td.replace(microseconds=0)

That would be nice.

In the meantime, this works for your use case:

td -= td % timedelta(seconds=1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top