[英]What is a solution to this error TypeError: strptime() argument 1 must be str, not datetime.date
[英]TypeError: strptime() argument 1 must be str, not datetime.date Python
在將日期轉換為字符串時遇到問題,
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'
更換
from_date = 2018-01-01
至
from_date : 2018-01-01
在ini文件中
經過測試的代碼:
import configparser
import datetime
config = configparser.ConfigParser()
config.read('Test.ini')
print (config['DEFAULT']['date'])
from_date = config['DEFAULT']['date']
print(type(from_date))
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
print (from_date)
而Test.ini是
[DEFAULT]
date : 2018-1-1
輸出是:
2018-1-1
<class 'str'>
2018-01-01
根據docs , datetime.strptime()
方法接受date_string
作為第一個參數。 所以,我嘗試了這個:
import datetime
test = datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date()
print(test)
#datetime.date(2018, 1, 1)
如果我執行from_date = 2018-01-01
,則會收到來自from_date
type
的invalid token
錯誤:
from_date = 2018-01-01
print(type(from_date))
File "<ipython-input-7-9e5449277912>", line 2
from_date = 2018-01-01
^
SyntaxError: invalid token
這意味着from_date
必須為字符串。 您可以使用from_date = '2018-01-01'
並且可以正常工作。 如果現在檢查from_date
的類型,我將得到類string
的類型:
from_date = '2018-01-01'
print(type(from_date))
#<class 'str'>
但是,當我查看第一個Traceback日志時,它將引發TypeError
。 這意味着from_date
存儲的值的類型為datetime.date
。 考慮以下:
import datetime
from_date = datetime.date(2018, 1, 1)
test = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date()
print(test)
#2018-01-01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.