0

I have a csv file consists of data (column = 'date') similar to 2017-W01, 2017-W02, 2018-W07 and so on. How can I make Python read this as date?

I have tried indexing the date column

import pandas as pd
df = pd.read_csv(r'input.csv', parse_dates=True, index_col='date')
df.head()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
greencar
  • 315
  • 1
  • 4
  • 18
  • 2
    That's not a *date*, it's a period pointing to the first week of 2017 etc. If you want to convert this to a date you'll have to decide which day in the week you want. You should probably modify your program to handle week numbers instead of specific dates – Panagiotis Kanavos Oct 14 '19 at 15:38
  • @PanagiotisKanavos okey, how can I do that in the actual code? – greencar Oct 14 '19 at 15:48
  • There's no `Or`. You can't just pick the "middle" of the week either, even you won't remember this and assume it's eg Sunday or Monday after a while. Pick one. Calculate the start of that week then add as many days as you need to get the day you want. It's *far better* though to use the actual data ie week numbers instead of assuming (ie inventing) some date that may or may not have meaning for your business case. – Panagiotis Kanavos Oct 14 '19 at 15:50
  • I know what needs to be done, I am unable to code it. – greencar Oct 14 '19 at 15:52
  • Possible duplicate of [Get date from week number](https://stackoverflow.com/questions/17087314/get-date-from-week-number) – Panagiotis Kanavos Oct 14 '19 at 15:57

1 Answers1

0

Suppose, you can collect the date from the csv file. To convert this data to datetime format you can use datetime lib:

    import datetime as D
    parsed_date = '2017-W01' # suppose, you got it from a cvs document in str format
    date = D.datetime.strptime(parsed_date, '%Y-W%W')
    print(date) # datetime.datetime(2017, 1, 1, 0, 0)
    print(date.year, date.month) # 2017, 1
    print(str(date)) # '2017-01-01 00:00:00'

link to docs: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

leucopterus
  • 31
  • 2
  • 6