numpy / numpy/numpy

Function for converting datetime.time to np.timedelta64

Open
#5,671 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

component: numpy.datetime64
Dominant language
Python
Stars
32.8k
Forks
12.8k
Avg merge
1d 7h
Merged PRs (30d)
197

Description

like np.timedelta64s, datetime.times are a relative measure of time (time since midnight). However, there is no easy method to convert from and array of datetime.times to np.timeteltas. About the simplest way is:

t = datetime.time(4,30)
td = np.array(datetime.timedelta(hours=t.hour, minutes=t.minute), dtype=np.timedelta64)

But this doesn't work with arrays of datetimes. The other option is to datetime.combine the datetime.times with an arbitrary datetime.date, and then subtract a datetime.datetime with the same date at midnight from them, to get a datetime.timedelta, and convert that. Convoluted as hell, and it also doesn't work with arrays.

It'd be nice to just ignore datetime.time altogether - to me it seems like a stupid datatype, when datetime.timedelta already exists, and has no practical difference. But there are cases when it can't be avoided. For example, pandas converts all date/time indexes into Timeindexes, which are based on datetimes. And when you do something like df.groupby(df.index.time).mean() (to get an average daily cycle), the resultant dataframe is indexed by datetime.time objects. This is a pretty common precedure, for me at least, and it'd be really good to be able to convert those times back in to something useful, like timedelta64s.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the scalar example with datetime.time, datetime.timedelta, np.array, and np.timedelta64, then compare it with an array of datetime.time values and the datetime.combine workaround described in the issue. Done means a clear conversion path supports arrays of datetime.time objects and produces useful np.timedelta64 values without requiring an arbitrary date.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
data
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.