0

I have this csv file which contains 2 columns: date of each day in 2021 and the related day of the week. the format of the date is dd/mm/yyyy, I need to write a program that requests a date in 2021 as input in the format of ‘mm/dd/yy’ and then gives its day of the week.

01/01/21,Friday 01/02/21,Saturday 01/03/21,Sunday 01/04/21,Monday 01/05/21,Tuesday 01/06/21,Wednesday 01/07/21,Thursday 01/08/21,Friday 01/09/21,Saturday

I tried datetime.datetime.strptime but it requires a string as the first item, I want to change the whole column.

1
  • 1
    Please, don't post images of data, code, etc. Copy/paste as text here. Also show your code minimal reproducible example. You need to iterate over rows and process each value OR use pandas and process whole column at once. Commented Feb 5, 2021 at 14:52

1 Answer 1

1

You can take the input from the user as a str, then check if it is date in your code and then convert it to a date to check the year and return the day based on the entered year. Something like the below code, assuming your dataframe name is df

import pandas as pd
from pandas.api.types import is_datetime64_any_dtype
import os
from uuid import uuid4



entered_date= input("Enter a date in 2021 in the formate dd/mm/yy")

## check if it is a date 
isDate= is_datetime64_any_dtype(entered_date)

if isDate:
    date = pd.to_datetime(entered_date, format='%d-%m-%y', errors='coerce')
    
    year = date.date.today().year
    ## check the year 2021
    if year!=2021:
        "The entered date is not in 2021"
    else:
        print(df.loc[df['date'] == date]['Day'])
else:
    "The entered value is not a valid date"
Sign up to request clarification or add additional context in comments.

3 Comments

thanks but my purpose is when user enter mm/dd/yyyy, the program will find the match date in csv(raw data in dd/mm/yyyy format), and return the day of the week of the mm/dd/yyyy input
just change the else to this format using loc: df.loc[df['Col1'] == foo]['Col2'] , I edited my code above. let me know if this works. to read from CVS using pandas import the data into a dataframe using: df = pd.read_csv(r'path/filename.csv') . The code above assumes the columns names for date and day are 'date', 'Day' respectively.
Why do you need a csv to get the day of the week for a given date?

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.