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.
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.
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.
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.
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
Additionally this reference may also assist you.
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html
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.datetime64
s 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')
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With