【问题标题】:python - Year-week combination for the end or beginning of a yearpython - 一年结束或开始的年-周组合
【发布时间】:2019-08-02 01:34:39
【问题描述】:

我想从日期构造 YYYY_WW 信息(其中 WW 是周数)。我正在为岁月的结束(开始)而苦苦挣扎,一周的一部分可能会落入下一年:

import datetime
import pandas as pd

# generate range of dates and extract YYYY_WW
dates_range = pd.date_range(start='2018-12-29', end='2019-01-02')
weeks = dates_range.strftime("%Y_%V")
print(weeks)

#Index(['2018_52', '2018_52', '2018_01', '2019_01', '2019_01'], dtype='object')

2018_01 显然是不正确的。有任何简单解决方法的提示吗?

【问题讨论】:

  • 你想要什么行为? ISO定义,意思是2018-12-31在2019年的第1周?
  • 我需要['2018_52', '2018_52', '2019_01', '2019_01', '2019_01'],它应该符合ISO,参见例如here

标签: python datetime strftime


【解决方案1】:

您正在寻找%G 指令:

带有世纪的 ISO 8601 年份代表包含 ISO 周的大部分时间 (%V)。

详情请见strftime() and strptime() behavior

例如:

import datetime
import pandas as pd

dates_range = pd.date_range(start='2018-12-29', end='2019-1-2')
weeks = dates_range.strftime('%G_%V')
print(weeks)
# Index(['2018_52', '2018_52', '2019_01', '2019_01', '2019_01'], dtype='object')

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2017-03-02
    相关资源
    最近更新 更多