Skip to content

ENH: align timedelta fractional seconds #57188

Open
@wjandrea

Description

@wjandrea

Feature Type

  • Adding new functionality to pandas
  • Changing existing functionality in pandas
  • Removing existing functionality in pandas

Problem Description

It's hard to read a column of timedeltas with fractional seconds of different precisions because it's not aligned, for example:

0             0 days 00:00:01
1      0 days 00:00:00.500000
2   0 days 00:00:00.333333333
dtype: timedelta64[ns]

It'd be easier to read like this:

0   0 days 00:00:01
1   0 days 00:00:00.500000
2   0 days 00:00:00.333333333
dtype: timedelta64[ns]

or

0   0 days 00:00:01.000000000
1   0 days 00:00:00.500000000
2   0 days 00:00:00.333333333
dtype: timedelta64[ns]

To reproduce:

s = 1 / pd.Series(np.arange(3)+1)
td = pd.to_timedelta(s, unit='s')
td

Feature Description

Add padding on the right.

In this case, it can be done by left-justifying to the largest size:

n = td.astype(str).apply(len).max()
td.astype(str).str.ljust(n)
0    0 days 00:00:01          
1    0 days 00:00:00.500000   
2    0 days 00:00:00.333333333
dtype: object

But of course, this wouldn't work for different numbers of days. For example:

td1 = pd.concat([td, pd.Series(pd.Timedelta(days=4000))])
0    0 days 00:00:01          
1    0 days 00:00:00.500000   
2    0 days 00:00:00.333333333
0    4000 days 00:00:00       
dtype: object

If timedeltas had a .replace() method so you could zero out the days, then it would work, but AFAIK such a method doesn't exist.

BTW, the same thing is already implemented for floats and datetimes.

>>> s*10
0    10.000000
1     5.000000
2     3.333333
dtype: float64
>>> pd.Timestamp(0) + td
0   1970-01-01 00:00:01.000000000
1   1970-01-01 00:00:00.500000000
2   1970-01-01 00:00:00.333333333
dtype: datetime64[ns]

Alternative Solutions

n/a

Additional Context

No response

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions