【发布时间】:2018-09-04 05:28:38
【问题描述】:
在将日期转换为字符串时遇到问题,
print(type(from_date))
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
我的 from_date 值在一个 ini 文件中,
from_date = 2018-01-01
我的 TraceBack 日志是,
Traceback (most recent call last):
File "Flexi_DailyToWeekly.py", line 87, in <module>
tuesday = get_data(session,from_keyspace, from_table, to_keyspace, to_table_tuesday, to_table_wednesday, to_table_thursday, to_table_friday, from_date, to_date)
File "Flexi_DailyToWeekly.py", line 11, in get_data
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d')
TypeError: strptime() argument 1 must be str, not datetime.date'
我使用了 type(from_date),它以字符串形式返回 from_date。
也试过了,
from_date = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date()
同样的错误仍然存在。
按照以下答案中的建议更改了 from_date,
from_date = "2018-01-01"
错误仍然存在,
Traceback (most recent call last):
File "Flexi_DailyToWeekly.py", line 82, in <module>
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data '"2018-01-01"' does not match format '%Y-%m-%d'
【问题讨论】:
-
使用 str(from_date)
-
也试过了。没用
-
没有。您的错误不会持续存在,它已更改。现在它表明您已设法在字符串 (
'"2018-01-01"') 中包含双引号,这是您最新错误的原因。为了让人们提供帮助,您将不得不展示更多的代码,而不仅仅是回溯和它出现的行 - 看看如何编写 minimal reproducible example。 -
尝试使用单引号而不是双引号,例如 from_date = '2018-01-01'