N
N
NikClik2018-12-11 16:20:31
Django
NikClik, 2018-12-11 16:20:31

How to compare string and datetime?

I have a string like "datetime.date(2018, 12, 11)" i need to compare it with datetime.date type. Something like:
if date_string == datetime.date:
do_something
How do I do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-12-11
@syschel

strptime convert string to date

from datetime import datetime
chday = datetime.strptime('datetime.date(2018, 12, 31)', 'datetime.date(%Y, %m, %d)')
today = datetime.today()
print(today < chday)
print(today > chday)
print(today == chday)
type(chday)

True
False
False
<class 'datetime.datetime'>

V
Vladimir Kuts, 2018-12-11
@fox_12

The simplest option (and the most insecure):

>>> import datetime
>>> in_str = "datetime.date(2018, 12, 11)"
>>> type(in_str)
<class 'str'>
>>> res = eval(in_str)
>>> res
datetime.date(2018, 12, 11)
>>> type(res)
<class 'datetime.date'>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question