Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/66065333/change-datetime-format-with-pythoncsv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...