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 ?

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

Also have a look at dateutil, whixh is an extensions to datetime.
@WwatlawW Yes. I know dateutil, but I wanted to keep it simple.
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
One of your dates is a datetime.date object, which is not the same. This link will help. Check how your start, date, end are defined. You can edit your question to include the newer lines now
Maybe I should not add as comment, I added for the others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.