【问题标题】:How to convert date into month name and day name in python?如何在python中将日期转换为月份名称和日期名称?
【发布时间】:2022-03-09 08:55:02
【问题描述】:

这是我在数据集 01/04/2021 中的原始日期,格式为日/月/年。 当我使用 pandas 时间戳 将日期转换为月份名称和日期名称时,它会将 12。 例如 2021 年 1 月 4 日 - 月 - 1 月 13/04/2021 - 月 - 四月。

代码

for attacks in df['Create Date/Time']:
  event_date.append(pd.Timestamp(attacks).day)
  event_month.append(pd.Timestamp(attacks).month_name())
  event_year.append (pd.Timestamp(attacks).year)
  event_day.append(pd.Timestamp(attacks).day_name())
  combined_time.append(pd.Timestamp(attacks).ctime())

【问题讨论】:

标签: python pandas date


【解决方案1】:

您可以这样做以实现我认为您的问题所要求的(或接近的):

import pandas as pd
records = [
    {'Create Date/Time': '01/04/2021'},
    {'Create Date/Time': '13/04/2021'}
]
df = pd.DataFrame(records)
print(df)
ser = pd.to_datetime(df['Create Date/Time'], dayfirst=True)
print("date series:\n", ser)
ser = ser.apply(lambda dt:' '.join((dt.month_name(), dt.day_name())))
print("month name and day name series:\n", ser)

输出:

  Create Date/Time
0       01/04/2021
1       13/04/2021
date series:
 0   2021-04-01
1   2021-04-13
Name: Create Date/Time, dtype: datetime64[ns]
month name and day name series:
 0    April Thursday
1     April Tuesday
Name: Create Date/Time, dtype: object

【讨论】:

  • @GoodOldGuy 很高兴听到我的回答有效。您的问题需要更多帮助吗?
猜你喜欢
  • 2018-12-21
  • 1970-01-01
  • 2021-01-01
  • 2021-08-21
  • 2020-03-24
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多