Facing issues while converting date to string,
print(type(from_date))
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
My from_date value is in an ini file,
from_date = 2018-01-01
My TraceBack log is,
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'
I've used type(from_date) which returns from_date as a string.
Also tried,
from_date = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date()
still the same error persists.
Changed from_date as suggested in the answers below,
from_date = "2018-01-01"
The error persisits,
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'
As per docs, The datetime.strptime()
method accepts a date_string
as the first argument. So, I tried this:
import datetime
test = datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date()
print(test)
#datetime.date(2018, 1, 1)
If I do from_date = 2018-01-01
, I get an invalid token
error for the type
of from_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
This means that from_date
must be a string. You could use from_date = '2018-01-01'
and that would work. If I check the type of from_date
now, I will get a type of class string
:
from_date = '2018-01-01'
print(type(from_date))
#<class 'str'>
But when I look at the first Traceback log, it raises a TypeError
. This means that the value stored in from_date
is of type datetime.date
. Consider the following:
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
Replace
from_date = 2018-01-01
to
from_date : 2018-01-01
in ini file
Tested with code :
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)
and Test.ini is
[DEFAULT]
date : 2018-1-1
output is :
2018-1-1
<class 'str'>
2018-01-01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With