MattR
MattR

Reputation: 5126

Get the Week Number between two Dates Pandas

I have a basic code snippet that I need to recreate in pandas:

import datetime as dt
date1 = dt.date(2016,10,10)
date2 = dt.date.today()
print('Week#', round((date2 - date1).days / 7 +.5))
# output: Week# 36

I have a datetime64[ns] datatype column and I cannot crack it. Using this basic example I'm stumped:

import pandas as pd
import numpy as np
import datetime as dt
dfp = pd.DataFrame({'A' : [dt.date(2016,10,6)]})
dfp['A'] = pd.to_datetime(dfp['A'])

def week(col):
    print((col.dt.date -  dt.date(2015, 10, 6)))

week(dfp['A']) #output: 366 days 

When I try re-creating the week number calculation I'm running into multiple errors: print((col.dt.date - dt.date(2015, 10, 6)).days) returns AttributeError: 'Series' object has no attribute 'days'

I'd like to try and solve this on my own so I can learn from the pain.

How do I return the pandas column values in terms of "number of days" or as an int like using the first calculation in the first code snippet? (ie, instead of 366 days, just 366)

If you're feeling adventurous how could i get the Week# xxx output in a more efficient way?

Upvotes: 2

Views: 982

Answers (1)

jezrael
jezrael

Reputation: 862581

I think you forget .dt:

dfp = pd.DataFrame({'A' : [date2]})
dfp['A'] = pd.to_datetime(dfp['A'])
print (dfp)

print (((dfp['A'].dt.date -  dt.date(2016, 10, 10)).dt.days / 7 + .5).round().astype(int))
0    36
Name: A, dtype: int32

Upvotes: 1

Related Questions