【问题标题】:Python: "object' does not match format '%Y-%W-%w'"Python: \"object\' 不匹配格式 \'%Y-%W-%w\'\"
【发布时间】:2023-01-31 02:03:17
【问题描述】:

我在 Spotfire 中使用 Python 并尝试将财政周转换为输入财政周的星期一的日期。

我试图实施 here 提供的解决方案,但无济于事。我的脚本如下:

import datetime
d= datetime.datetime.strptime(str(fw), "%Y-%W-%w")

输入值类似于以下值:

Input
2023-06-1
2023-08-1
2023-13-1
2023-12-1

错误的全文如下:

Could not execute function call 'date_from_fw'


Error executing Python script:

ValueError: time data '0        2021-17-1\n1        2023-11-1\n2        2023-12-1\n3        2021-24-1\n4        2022-39-1\n           ...    \n82248    2024-09-1\n82249    2024-10-1\n82250    2022-45-1\n82251    2022-33-1\n82252    2022-33-1\nName: fiscal_week_str, Length: 82253, dtype: object' does not match format '%Y-%W-%w'

Traceback (most recent call last):
  File "data_function.py", line 333, in _execute_script
    exec(compiled_script, self.globals)
  File "<data_function>", line 2, in <module>
  File "_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "_strptime.py", line 359, in _strptime
    (data_string, format))



   at Spotfire.Dxp.Data.DataFunctions.Executors.LocalPythonFunctionClient.<RunFunction>d__8.MoveNext()
   at Spotfire.Dxp.Data.DataFunctions.Executors.PythonScriptExecutor.<ExecuteFunction>d__11.MoveNext()
   at Spotfire.Dxp.Data.DataFunctions.DataFunctionExecutorService.<ExecuteFunction>d__8.MoveNext()

【问题讨论】:

  • fw 似乎是一个数组。我想你打算只将该数组的一个元素传递给strptime。现在你对此有什么问题?
  • 您的问题中没有足够的信息。被抱怨的数据看起来像是 Pandas 系列的字符串表示,我在 Spotfire 文档中看到一些东西说 Spotfire 专栏映射到熊猫系列。我们真的不知道你的意图。请阅读minimal reproducible example
  • @mkrieger1,我相信你是对的,Spotfire 将所有列值作为数组传递。从 Python 的 strptime 文档来看,该函数似乎只接受单个字符串值。这是否意味着我应该遍历输入数组,将每个值插入strptime,并将每个结果附加到输出数组d

标签: python date spotfire


【解决方案1】:

找到了不使用 strptime 函数的解决方案。这是假设列系列输入的财政周值格式为“YYYY-WW”。

import datetime
import pandas as pd

# fw is input in format 'YYYY-WW' 
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column 
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2020-02-19
    • 2021-02-23
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多