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

前端 未结 26 1471
迷失自我
迷失自我 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:26

    We can take help of Pandas:

    import pandas as pd
    

    As mentioned above in the problem We have:

    datetime(2017, 10, 20)
    

    If execute this line in the jupyter notebook we have an output like this:

    datetime.datetime(2017, 10, 20, 0, 0)
    

    Using weekday() and weekday_name:

    If you want weekdays in integer number format then use:

    pd.to_datetime(datetime(2017, 10, 20)).weekday()
    

    The output will be:

    4
    

    And if you want it as name of the day like Sunday, Monday, Friday, etc you can use:

    pd.to_datetime(datetime(2017, 10, 20)).weekday_name
    

    The output will be:

    'Friday'

    If having a dates column in Pandas dataframe then:

    Now suppose if you have a pandas dataframe having a date column like this: pdExampleDataFrame['Dates'].head(5)

    0   2010-04-01
    1   2010-04-02
    2   2010-04-03
    3   2010-04-04
    4   2010-04-05
    Name: Dates, dtype: datetime64[ns]
    

    Now If we want to know the name of the weekday like Monday, Tuesday, ..etc we can use .weekday_name as follows:

    pdExampleDataFrame.head(5)['Dates'].dt.weekday_name
    

    the output will be:

    0    Thursday
    1      Friday
    2    Saturday
    3      Sunday
    4      Monday
    Name: Dates, dtype: object
    

    And if we want the integer number of weekday from this Dates column then we can use:

    pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())
    

    The output will look like this:

    0    3
    1    4
    2    5
    3    6
    4    0
    Name: Dates, dtype: int64
    

提交回复
热议问题