3

i have below code where it checks if the date is in between start and end dates and returns its filename.

import pandas as pd
def loaddata():

global dict1
dict1 = {}

with open('load.csv', mode='r') as f:
    for z in csv.DictReader(f, skipinitialspace=True):
        Start_date = pd.to_datetime(z['Start_date'])
        End_date = pd.to_datetime(z['End_date'])
        File_type = z['File_type']
        File_name = z['File_name']

        if File_name not in dict1:
            dict1[File_name] = {}
        if File_type not in dict1[File_name]:
            dict1[File_name][File_type] = (Start_date, End_date)

# dict1 gives  >> {'file_name': {'type1': (Timestamp('2019-05-06 00:00:00'), Timestamp('2019-12-31 00:00:00'))},
# 'file_name1': {'type2': (Timestamp('2018-05-06 00:00:00'), Timestamp('2018-12-31 00:00:00'))}}

def fn(date, filetype):
    for filename, range in dict1.items():
        if filetype in range:
            start, end = range[filetype]
            if start <= date <= end:
                return filename


new_date = pd.to_datetime('2019-12-21')
print(fn(new_date, 'type1'))   
# >> returns filename

I used pandas for converting the string dates to date format. Is there any way to convert it without pandas ?

kate
  • 55
  • 7

1 Answers1

3

Yes of course:

from datetime import datetime

date_string = "2017/01/31"

date = datetime.strptime(date_string, "%Y/%m/%d")

print(date)
# datetime.datetime(2017, 1, 31, 0, 0)

pissall
  • 7,109
  • 2
  • 25
  • 45
  • Also have a look at **dateutil**, whixh is an extensions to **datetime**. – WwatlawW Nov 15 '19 at 12:35
  • @WwatlawW Yes. I know `dateutil`, but I wanted to keep it simple. – pissall Nov 15 '19 at 12:36
  • I tried `Start_date = datetime.datetime.strptime(row['Start_date'], "%m/%d/%Y")` and i get `if start <= date <= end: TypeError: can't compare datetime.datetime to datetime.date` error – kate Nov 15 '19 at 12:38
  • One of your dates is a `datetime.date` object, which is not the same. This [link](https://stackoverflow.com/questions/1937622/convert-date-to-datetime-in-python) will help. Check how your `start`, `date`, `end` are defined. You can edit your question to include the newer lines now – pissall Nov 15 '19 at 12:40
  • Maybe I should not add as comment, I added for the others. – WwatlawW Nov 15 '19 at 13:01