TypeError:strptime()参数1必须是str,而不是datetime.date Python

问题描述 投票:0回答:2

在将日期转换为字符串时遇到问题,

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'
python datetime
2个回答
0
投票

更换

from_date = 2018-01-01

from_date : 2018-01-01

在这个文件中

测试代码:

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

0
投票

根据docsdatetime.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,我得到invalid token typefrom_date错误:

   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
© www.soinside.com 2019 - 2024. All rights reserved.