Home > Back-end >  Changing a string with dates into days after Jan. 1, 2010
Changing a string with dates into days after Jan. 1, 2010

Time:02-22

For the function below, I am inputting a string like "6/29/2020" and "8/10/2010" and I want to get a numbers of days after Jan. 1, 2010. For example, if I input "1/29/2010", I want the integer 29 to be returned.

Currently, I have gotten "6/29/2020" to a string "2020-06-29". Now I just need help with converting that string into the days after Jan. 1, 2010.

I feel like I have posted everything needed for you to help, but if you need more information, let me know. Thank You for helping me with this problem.

def day_conversion(dates):
  import datetime
  
  i = 0

  for day in dates:
        day = day.split('/')

        if len(day[0]) == 1:
              day[0] = f"0{day[0]}"
        if len(day[1]) == 1:
              day[1] = f"0{day[1]}"

        day = f"{day[2]}-{day[0]}-{day[1]}"

      #   day = date.format(day)
      #   from datetime import date
      #   day0 = date(2000, 1, 1)
      #   day = day - day0
        
        dates[i] = day
        i  = 1

  return dates

CodePudding user response:

datetime has a function for parsing dates, and subtracting two datetime objects gives a timedelta object with a .days attribute:

from datetime import datetime

def days_since_jan1_2010(date):
    dt = datetime.strptime(date, '%m/%d/%Y')
    diff = dt - datetime(2010, 1, 1)
    return diff.days

def day_conversion(dates):
    return [days_since_jan1_2010(d) for d in dates]

print(day_conversion(['6/29/2020', '8/10/2010', '1/1/2010', '1/2/2010']))

Output:

[3832, 221, 0, 1]

CodePudding user response:

Everything in the previous answer is correct, but just thought I'd point out that you were very nearly there if you include the commented out part in your code above except for the following points:

  1. from datetime import date needs to come before you try to use date.
  2. You want date.fromisoformat, not date.format.
  3. Your code has Jan 1 2000 but you state in your question that you want the number of days from Jan 1 2010.

If you substitute the commented part of your original code for the following four lines you should get the result you are after.

from datetime import date
day = date.fromisoformat(day)
day0 = date(2010, 1, 1)
day = day - day0
  • Related