Unpack timedelta and datetime

I would find it useful if timedelta and datetime unpacked into kwargs as

dict(**my_timedelta) == dict(days=..., seconds=..., microseconds=...)
dict(**my_datetime) == dict(year=..., month=..., day=..., hour=..., minute=..., second=..., microsecond=..., tzinfo=..., fold=...)

This came to mind as a result of this discussion but since it would require changes to 2 different modules to have any impact[1], I feel like this deserves its own discussion.

Two other areas where I have missed being able to unpack datetime/timedelta objects are:

  1. creating modified versions of datetime objects. For example, datetime(**my_datetime, tzinfo=None) would have felt like a natural way to strip the timezone info, in a way which my_datetime.replace(tzinfo=None) doesn’t.
  2. Putting datetimes into dataframes or databases, rarely I do want to have hour/minute/second columns. Being able to include data=f(..., cols={..., **dt, ...}) in one go would be both intuitive and convenient. The current technique is to use data=f(..., cols={..., "dt": dt, ...}) and then include some post-processing steps to convert the “dt” column into its component columns, which is slightly bothersome boilerplate. Or to spell out explicitly data=f(..., cols={..., "year":dt.year, "month":dt.month, "day":dt.day, "hour":dt.hour, "minutes":dt.minutes, "seconds": dt.seconds, ...}) which is more work (both to type and to read) and leaves more room for errors.

I could also conceive of people wanting to use such unpacking for json.

datetime and timedelta already have machinery to calculate this dict, because that’s what they display as their repr. eg:

print(f'{timedelta!r}')
>>>datetime.timedelta(days=1, seconds=22028, microseconds=9)
print(f'{time=!r}')
>>>datetime.datetime(2025, 1, 2, 6, 7, 8, 9, tzinfo=datetime.timezone.utc)

  1. The idea is that you could have a sleep function that you could call as sleep(**duration) instead of sleep(duration.total_seconds()) ↩︎