简体   繁体   English

如何将星期几、月份、日期转换为年 - 月 - 日期

[英]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:我在 pandas 列中有从 2018 年到 2021 年的日期,它们看起来像这样:

Date日期
Sun, Dec 30 12 月 30 日,星期日
Mon, Dec 31 12 月 31 日,星期一

Any idea how I can convert this to:知道如何将其转换为:

Date日期
Dec 30 2018 2018 年 12 月 30 日
Dec 31 2018 2018 年 12 月 31 日

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.如前所述,您可能需要定义一个年份范围,因为 12 月 30 日(例如)有可能在一年多的时间里正好是星期日。 Otherwise, it is possible to collect a list of years where the input (Sun, Dec 30) is valid.否则,可以收集输入(12 月 30 日星期日)有效的年份列表。 You will probably need to use datetime to convert your strings to a Python readable format.您可能需要使用datetime将字符串转换为 Python 可读格式。

you can iterate the years from 2018 to 2022 to get every target date's weekday name, then find the match year.您可以迭代从 2018 年到 2022 年的年份以获取每个目标日期的工作日名称,然后找到匹配年份。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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