Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding day of the week for a datetime64

Apologies if this is an easy one but I can't see anything in the numpy documentation. I have a datetime64 and I'd like to find out which day of the week it is.

Unlike python datetime, datetime64 doesn't seem to have a .weekday() function. However it does have a busday_offset() function, which implies it must know behind-the-scenes what day of the week a given date is. Any help greatly appreciated.

like image 771
Chris J Harris Avatar asked Sep 19 '18 05:09

Chris J Harris


People also ask

How do I get the day of the week in Python?

isoweekday() to get a weekday of a given date in Python Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.

How do I extract a day from a date column in Python?

dt. dayofweek returns the day of the week ranging from 0 to 6 where 0 denotes Monday and 6 denotes Sunday. Output : Example 2 : Pandas.

What is datetime64?

New in version 1.7. 0. Starting in NumPy 1.7, there are core array data types which natively support datetime functionality. The data type is called datetime64 , so named because datetime is already taken by the Python standard library.


2 Answers

Please look at the following related SO question:

Get weekday/day-of-week for Datetime column of DataFrame

I understand that your data is a numpy array, it may be useful to convert your data into a dataframe format via pandas. This is shown below.

import pandas as pd
df = pd.DataFrame(numpyArray)

Provided your data is now in a dataframe, then the below code (taken from the above link), should provide you with the weekday you are after.

df['weekday'] = df['Timestamp'].dt.dayofweek

Sample Output

Additionally this reference may also assist you.

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html

like image 174
IronKirby Avatar answered Oct 16 '22 16:10

IronKirby


If you're looking for a genuinely vectorized numpy approach, you could do:

def day_of_week_num(dts):
    return (dts.astype('datetime64[D]').view('int64') - 4) % 7

It's a bit hacky, and just takes advantage of the fact that numpy.datetime64s are relative to the unix epoch, which was a Thursday.

(I don't know if this is an implementational detail that could change without notice, but you can always check with assert np.zeros(1).astype('datetime64[D]') == np.datetime64('1970-01-01', 'D').)

like image 34
jwdink Avatar answered Oct 16 '22 15:10

jwdink