【问题标题】:How can I get in datetime week-year? [duplicate]我怎样才能进入日期时间周年? [复制]
【发布时间】:2021-05-27 21:15:52
【问题描述】:

我有follow df:

time_series                date   sales
store_0051_item_909446    3/2021    4.0
store_0051_item_909446    4/2021    4.0
store_0051_item_909446    5/2021    1.0
store_0053_item_909446    6/2021    1.0
store_0059_item_909446    7/2021    0.0

作为“日期”周/年。 我想在日期时间转换这个字段:周年。 我尝试了以下代码:

df['date'] = df['date'].apply(lambda x: datetime.strptime(x, '%W/%Y'))

但是,返回下面的df:

time_series                  date       sales
store_0051_item_909446    2021-01-01    4.0
store_0051_item_909446    2021-01-01    4.0
store_0051_item_909446    2021-01-01    1.0
store_0053_item_909446    2021-01-01    1.0
store_0059_item_909446    2021-01-01    0.0

我在代码中遗漏了什么?

【问题讨论】:

  • 这能回答你的问题吗? Get date from week number
  • 是的,谢谢! :D
  • 从 Python 的文档中非常不清楚 %W 除非与 w% 一起使用 - 甚至可能是一个错误吗?
  • 是的,Grismar... 有道理,我希望返回这个:W-Y: 45-2020。我的疑问是:在日期时间这种格式不存在?

标签: python datetime


【解决方案1】:
df['week'] = df['date'].apply(lambda x: x.isocalendar()[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多