How do I get the day of week given a date?

前端 未结 26 1417
迷失自我
迷失自我 2020-11-22 04:40

I want to find out the following: given a date (datetime object), what is the corresponding day of the week?

For instance, Sunday is the first day, Mond

相关标签:
26条回答
  • 2020-11-22 05:08
    import datetime
    int(datetime.datetime.today().strftime('%w'))+1
    

    this should give you your real day number - 1 = sunday, 2 = monday, etc...

    0 讨论(0)
  • 2020-11-22 05:09

    datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :

    from dateutil import parser
    parser.parse('January 11, 2010').strftime("%a")
    

    The output that you get from this is 'Mon'. If you want the output as 'Monday', use the following :

    parser.parse('January 11, 2010').strftime("%A")
    

    This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.

    0 讨论(0)
  • 2020-11-22 05:10

    Below is the code to enter date in the format of DD-MM-YYYY you can change the input format by changing the order of '%d-%m-%Y' and also by changing the delimiter.

    import datetime
    try:
        date = input()
        date_time_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
        print(date_time_obj.strftime('%A'))
    except ValueError:
        print("Invalid date.")
    
    0 讨论(0)
  • 2020-11-22 05:12
    import datetime
    import calendar
    
    day, month, year = map(int, input().split())
    my_date = datetime.date(year, month, day)
    print(calendar.day_name[my_date.weekday()])
    

    Output Sample

    08 05 2015
    Friday
    
    0 讨论(0)
  • 2020-11-22 05:13

    If you have dates as a string, it might be easier to do it using pandas' Timestamp

    import pandas as pd
    df = pd.Timestamp("2019-04-12")
    print(df.dayofweek, df.weekday_name)
    

    Output:

    4 Friday
    
    0 讨论(0)
  • 2020-11-22 05:14

    Say you have timeStamp: String variable, YYYY-MM-DD HH:MM:SS

    step 1: convert it to dateTime function with blow code...

    df['timeStamp'] = pd.to_datetime(df['timeStamp'])
    

    Step 2 : Now you can extract all the required feature as below which will create new Column for each of the fild- hour,month,day of week,year, date

    df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
    df['Month'] = df['timeStamp'].apply(lambda time: time.month)
    df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
    df['Year'] = df['timeStamp'].apply(lambda t: t.year)
    df['Date'] = df['timeStamp'].apply(lambda t: t.day)
    
    0 讨论(0)
提交回复
热议问题