简体   繁体   中英

How can I convert day of week, Month, Date to Year - Month - Date

I have dates from 2018 until 2021 in a pandas column and they look like this:

Date
Sun, Dec 30
Mon, Dec 31

Any idea how I can convert this to:

Date
Dec 30 2018
Dec 31 2018

In the sense that is it possible that knowing the day of the week ie (monday, tuesday etc) is it possible to get the year of that specific date?

I would take a look at this conversation. As mentioned, you will probably need to define a range of years, since it is possible that December 30th (for example) falls on a Sunday in more than one year. Otherwise, it is possible to collect a list of years where the input (Sun, Dec 30) is valid. You will probably need to use datetime to convert your strings to a Python readable format.

you can iterate the years from 2018 to 2022 to get every target date's weekday name, then find the match year.

df = pd.DataFrame({'Date': {0: 'Sun, Dec 30',
                            1: 'Mon, Dec 31'}})
for col in range(2018, 2022):
    df[col] = '%s' % col + df['Date'].str.split(',').str[-1]
    df[col] = pd.to_datetime(df[col], format='%Y %b %d').dt.strftime('%a, %b %d')

dfn = df.set_index('Date').stack().reset_index()
cond = dfn['Date'] == dfn[0]
obj = dfn[cond].set_index('Date')['level_1'].rename('year')

result:

print(obj)

    Date
    Sun, Dec 30    2018
    Mon, Dec 31    2018
    Name: year, dtype: int64

print(df.join(obj, on='Date'))

              Date         2018         2019         2020         2021  year
    0  Sun, Dec 30  Sun, Dec 30  Mon, Dec 30  Wed, Dec 30  Thu, Dec 30  2018
    1  Mon, Dec 31  Mon, Dec 31  Tue, Dec 31  Thu, Dec 31  Fri, Dec 31  2018


df_result = obj.reset_index()
df_result['Date_new'] = df_result['Date'].str.split(',').str[-1] + ' ' + df_result['year'].astype(str)
print(df_result)

              Date  year      Date_new
    0  Sun, Dec 30  2018   Dec 30 2018
    1  Mon, Dec 31  2018   Dec 31 2018

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