【问题标题】:How to change string date range to start and end date?如何将字符串日期范围更改为开始和结束日期?
【发布时间】:2019-12-11 08:25:17
【问题描述】:

我正在尝试将字符串日期范围(例如 7 月 1 日至 30 日)分隔为作为日期时间的开始日期和结束日期(例如 2019 年 7 月 1 日和 2019 年 7 月 30 日)。如何转换?

我尝试过将字符串分解成碎片,但我相信使用正则表达式的唯一方法。

列中的字符串示例:

    "1 to 30 of July"
    "10 to 12 of August"
    "20 of January to 10 of February"

我用过^(\d{1,2})\s([a-z]{2})\s(\d{1,2})\s([a-z]{2})\s(\w{1,13}),但我错过了 M 的 D 到 M 的 D。

都是2019年的

【问题讨论】:

  • 他们总是D of M吗?
  • 你用正则表达式尝试过什么吗?你能发布你的努力吗?
  • 我试过 ^\d{1,2}\s[az]{2}\s\d{1,2}\s[az]{2}\s\w{ 1,13} 但我无法将它们分组...
  • 可能还有另一个字符串,例如20th of January to 10th of February ?
  • 不,'th' 已被删除

标签: python regex pandas datetime


【解决方案1】:

我们可以使用带有Series.str.extractall 的正则表达式从您的数据中提取数字和月份。然后我们最终将字符串连接在一起:

days = df['Date'].str.extractall('(\d+)').unstack()

months = '('+'|'.join(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])+')'
monthnames = df['Date'].str.extractall(months).unstack().ffill(axis=1)

df = days + ' ' + monthnames.ffill(axis=1)
df.columns=['date_start', 'date_end']

输出

   date_start     date_end
0      1 July      30 July
1   10 August    12 August
2  20 January  10 February

如果您希望它们采用不带月份名称的日期格式:

df.apply(lambda x: pd.to_datetime(x, format='%d %B').dt.strftime('%m-%d'))

  date_start date_end
0      07-01    07-30
1      08-10    08-12
2      01-20    02-10

【讨论】:

    【解决方案2】:

    以下将提取日期和月份:

    # update your month list properly
    months = ['January', 'February', 'July', 'August']
    
    # pattern
    pattern = f'(\d+) (?:of ({m}))?\s?to (\d+).*({m})'
    
    # extract:
    s.str.extract(patterns)
    

    输出:

        0        1   2         3
    0   1      NaN  30      July
    1  10      NaN  12    August
    2  20  January  10  February
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2022-01-23
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多