0

Docs say I can pull out the week of the year from the timestamp:

pd.to_datetime('03-01-2021').week -> 9

But I need weeks since the epoch.

I have to do gaps and islands analysis, so I need to wind up with sequence increasing by 1 per week.

A stupidly naive implementation would be to do something like this

mydatetime.year * WEEKS_IN_YEAR + mydatetime.week

But besides problems I'm not accounting for, I don't believe there is an actual WEEK_IN_YEAR integer.

naftalimich
  • 401
  • 4
  • 13
  • 1
    what is your epoch? and also, what is your definition of "week"? just seven days, iso-week, ...? – FObersteiner Jan 21 '21 at 18:21
  • Data goes back five years. So any epoch earlier than that is okay. How the weeks is defined? Hmm. I haven't thought deeply about that, but assumed that there is a convention used in the standard libraries as there are provided methods to obtain it in context of the year @MrFuppes (I would choose Monday through Sunday, if given a choice) – naftalimich Jan 21 '21 at 18:25
  • I have a potential solution. Pandas has a period constants with which to generate date ranges. Among them are week starting by day n like Monday. I can generate a date range from epoch using his period, search for where in that range my datetime belongs, and use the position in the array. I wish there was a more direct solution @MrFuppes – naftalimich Jan 21 '21 at 18:37

1 Answers1

0

My solution

from datetime import timedelta
import pandas as pd

jan1 = pd.to_datetime('01-01-2021')
march1 = pd.to_datetime('03-01-2021')
epoch = pd.to_datetime('1970-01-01')

monday_week_of_jan1 = (jan1 - timedelta( days=jan1.weekday() ))
monday_week_of_march3 = (march1 - timedelta(days=march1.weekday()))
monday_week_of_epoch = (epoch - timedelta(days=epoch.weekday()))

jan_1_weeks_from_epoch = (monday_week_of_jan1 - monday_week_of_epoch).days // 7
march_3_weeks_from_epoch = (monday_week_of_march3 - monday_week_of_epoch).days // 7

[jan_1_weeks_from_epoch, march_3_weeks_from_epoch]

=> [2661, 2670]

Adapted from https://stackoverflow.com/a/14191915/1248361

naftalimich
  • 401
  • 4
  • 13