简体   繁体   中英

Change datetime format with python(CSV)

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM